简单的dfs递归,我们把每个访问到的‘1’,都对其进行dfs,使得与他相邻的‘1’都置为‘0’
/**
* @author johnsondu
* @problem Number of Islands
* @url https://leetcode.com/problems/number-of-islands/
* @timeComlexity O(n^2)
* @spaceComplexity O(1)
* @strategy See code.
*/
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
class Solution {
public:
void dfs(int x, int y, int row, int col, vector<vector<char>>& grid)
{
for(int i = 0; i < 4; i ++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < row && tx >= 0 && ty < col && ty >= 0) {
if(grid[tx][ty] == '1') {
grid[tx][ty] = '0';
dfs(tx, ty, row, col, grid);
}
}
}
}
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
if(row == 0) return 0;
int col = grid[0].size();
if(col == 0) return 0;
int cnt = 0;
for(int i = 0; i < row; i ++)
for(int j = 0; j < col; j ++) {
if(grid[i][j] == '1') {
cnt ++;
dfs(i, j, row, col, grid);
}
}
return cnt;
}
};