lintcode433 岛屿的个数

岛屿的个数 

给一个01矩阵,求不同的岛屿的个数。

0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。

样例

在矩阵:

[
  [1, 1, 0, 0, 0],
  [0, 1, 0, 0, 1],
  [0, 0, 0, 1, 1],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1]
]

中有 3 个岛.

 1 class Solution {
 2 public:
 3     /**
 4      * @param grid a boolean 2D matrix
 5      * @return an integer
 6      */
 7     int numIslands(vector<vector<bool>>& grid) {
 8         // Write your code here
 9         if(grid.empty() || grid[0].empty())
10             return 0;
11         int m = grid.size(), n = grid[0].size();
12         int count = 0;
13         for(int i = 0; i < m; ++i){
14             for(int j = 0; j < n; ++j){
15                 if(grid[i][j]){
16                     ++count;
17                     dfs(grid, i, j);
18                 }
19             }
20         }
21         return count;
22     }
23     void dfs(vector<vector<bool> > &grid, int x, int y){
24         if((x < 0) || (y < 0) || (x >= grid.size()) || (y >= grid[0].size()) || !grid[x][y])
25             return;
26         grid[x][y] = false;
27         dfs(grid, x - 1, y);
28         dfs(grid, x, y - 1);
29         dfs(grid, x + 1, y);
30         dfs(grid, x, y + 1);
31     }
32 };
原文地址:https://www.cnblogs.com/gousheng/p/7635002.html