[LeetCode] Number of Islands
阿新 • • 發佈:2017-10-10
一個 code emp nec island map const 不用 water
Given a 2d grid map of ‘1‘
s (land) and ‘0‘
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
尋找島嶼的個數。核心思想是利用一個visited二維數組來標誌一個數(1)是否被訪問過。在grid二維數組中局部使用廣度優先遍歷來判斷並尋找島嶼。如果訪問過則下次就不用將其再次計算。
class Solution { public: int numIslands(vector<vector<char>>& grid) { if (grid.empty() || grid[0].empty()) return 0; int cnt = 0; const int M = grid.size();const int N = grid[0].size(); vector<vector<bool>> visited(M, vector<bool>(N, false)); for (int i = 0; i != M; i++) { for (int j = 0; j != N; j++) { if (!visited[i][j] && grid[i][j] == ‘1‘) { numIslandsCore(grid, visited, i, j); cnt++; } } } return cnt; } void numIslandsCore(vector<vector<char>>& grid, vector<vector<bool>>& visited, int i, int j) { if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && !visited[i][j] && grid[i][j] == ‘1‘) { visited[i][j] = true; numIslandsCore(grid, visited, i - 1, j); numIslandsCore(grid, visited, i, j - 1); numIslandsCore(grid, visited, i, j + 1); numIslandsCore(grid, visited, i + 1, j); } } }; // 6 ms
[LeetCode] Number of Islands