描述:
给一个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
个岛.
class Solution {
public:
/**
* @param grid a boolean 2D matrix
* @return an integer
*/
int numIslands(vector<vector<bool>>& grid) {
// Write your code here
if(grid.empty() || grid[0].empty())
return 0;
// height为矩阵的高, width为矩阵的宽
int height = grid.size(), width = grid[0].size();
int count = 0; // count记录岛屿的个数
//遍历矩阵,遇到为true的点,岛屿的个数加1,并将彼此相邻且为true的点改为false
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
if(grid[i][j]){
count += 1; //岛屿的个数加1
search(grid, i, j); //将相邻为true的点改为false
}
}
}
return count;
}
void search(vector<vector<bool>>& grid, int x, int y){
int height = grid.size();
int width = grid[0].size();
// 越界或则当前点为false返回
if((x < 0) || (y < 0) || (x >= height) || (y >= width) || !grid[x][y])
return;
grid[x][y] = false;
search(grid, x - 1, y); //搜索上面的点
search(grid, x, y - 1); //搜索左面的点
search(grid, x + 1, y); //搜索下面的点
search(grid, x, y + 1); //搜索右面的点
}
};