题解
这道题做了若干遍,推荐的做法是drown every island的做法,也就是用初始的grid矩阵同时作为记忆矩阵,那么可以省去一个visited矩阵。这里作为DFS练习,还是套用visited矩阵的做法。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.empty()) return 0;
int num = 0;
vector<vector<bool>> visited(grid.size(), vector<bool>(grid[0].size(), false));
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[0].size(); j++) {
if(grid[i][j] == '1' && !visited[i][j]) {
search(grid, visited, i, j);
num++;
}
}
}
return num;
}
void search(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) {
if(x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size()) return;
if(grid[x][y] == '0') return;
if(visited[x][y]) return;
visited[x][y] = true;
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for(int k = 0; k < 4; k++) {
int xx = x + dirs[k][0];
int yy = y + dirs[k][1];
search(grid, visited, xx, yy);
}
}
};