class Solution {
public:
//0跳,重复跳
int dirt[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
void re(vector<vector<char> >& grid, int i, int j){
grid[i][j] = '0';//1->0
for(int k=0; k<4; k++){
int nexti = i+dirt[k][0];
int nextj = j+dirt[k][1];
if(nexti>=0 && nexti<grid.size() && nextj>=0 && nextj<grid[0].size() && grid[nexti][nextj]=='1'){
re(grid, nexti, nextj);
}
}
}
int solve(vector<vector<char> >& grid) {
int count = 0;
for(int i=0; i<grid.size(); i++){
for(int j=0; j<grid[0].size(); j++){
if(grid[i][j]=='1'){
re(grid, i, j);
count++;
}
}
}
return count;
}
};
回溯部分主要是遍历完一个完整的岛屿,并将遍历到的合法岛屿点置0,故再往下一个岛屿的时候,不会和已经遍历过的岛屿点冲突。

京公网安备 11010502036488号