1. Title description
Given a two-dimensional grid composed of '1' (land) and '0' (water), please count the number of islands in the grid.
Islands are always surrounded by water, and each island can only be formed by connecting adjacent land in the horizontal and/or vertical direction.
In addition, you can assume that all four sides of the grid are surrounded by water.
Example:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
[ "1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]
]
output: 1
example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
[ "0","0","1","0","0"],
["0","0","0","1","1"]
]
output: 3
2. Solution
This is a DFS problem. Continue to deepen from one point to four directions, and if you encounter "water" or exceed the boundary, you will retreat.
class Solution {
public:
int numIslands(vector<vector<char>>& grid){
int m = grid.size();
int n = grid[0].size();
int num = 0;
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++){
if(grid[i][j] == 1){
//一个岛屿
DFS(i,j,grid); //把这个连通块都标记为0
num += 1; //岛屿数量++
}
}
return num;
}
void DFS(int x, int y, vector<vector<char>>& isConnected){
if(x<0||x>=isConnected.size()||y<0||y>=isConnected[0].size()) //回退条件
return;
if(isConnected[x][y] == '0') //回退条件
return;
isConnected[x][y] = '0'; //go!
DFS(x+1,y,isConnected);
DFS(x,y+1,isConnected);
DFS(x-1,y,isConnected);
DFS(x,y-1,isConnected);
}
};