题目:
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.
思路:
只要找到一个为“1”的点,就从这个点开始深度优先遍历,把所有连接在一起的“1”点都置0。然后重复前述操作。每操作一次,就是操作的一个岛屿。
代码实现:
class Solution {
public:
bool checkCoord(vector<vector<char>>& grid, int r, int c){
int rows = grid.size();
int cols = grid[0].size();
if (r >= 0 && r < rows && c >= 0 && c < cols){
return true;
}
return false;
}
void f(vector<vector<char>>& grid, int r, int c){
if (checkCoord(grid, r, c) && grid[r][c] == '1'){
grid[r][c] = '0';
f(grid, r-1, c);
f(grid, r+1, c);
f(grid, r, c-1);
f(grid, r, c+1);
}
return ;
}
int numIslands(vector<vector<char>>& grid) {
int rows = grid.size();
if (rows <= 0){
return 0;
}
int cols = grid[0].size();
int count = 0;
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
if (grid[i][j] == '1'){
++count;
f(grid, i, j);
}
}
}
return count;
}
};