200. Number of Islands
题目: 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
分析: 这道题可以用深度优先搜索解决, 如果当前位置为1
, 则置当前位置为'0'(已访问), 并以当前位置中心递归的遍历当前位置的上, 下, 左, 右四个位置. 直到grid
中所有位置均为0
. 代码如下:
code:
class Solution {
public:
int numIslands(vector<vector<char> >& grid) {
if(grid.empty()) return 0;
int num = 0;
int row = grid.size();
int col = grid[0].size();
for (int i = 0; i < row; ++i){
for (int j = 0; j < col; ++j) {
if (grid[i][j] == '1') {
helper(i, j, grid);
num++;
}
}
}
return num;
}
void helper(int row, int col, vector<vector<char>>& grid) {
grid[row][col] = '0';
if (row-1>=0 && grid[row-1][col]=='1') {
helper(row-1, col, grid);
}
if (row+1<grid.size() && grid[row+1][col]=='1') {
helper(row+1, col, grid);
}
if (col-1>=0 && grid[row][col-1]=='1') {
helper(row, col-1, grid);
}
if (col+1<grid[0].size() && grid[row][col+1]=='1') {
helper(row, col+1, grid);
}
}
};