参考:
https://leetcode.com/problems/number-of-islands/discuss/56589/C%2B%2B-BFSDFS
DFS:(递归实现)
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
islands++;
eraseIslands(grid, i, j); //从矩阵的任一个元素开始搜索
}
}
}
return islands;
}
private:
void eraseIslands(vector<vector<char>>& grid, int i, int j) {
int m = grid.size(), n = grid[0].size();
if (i < 0 || i == m || j < 0 || j == n || grid[i][j] == '0') {
return;
}
grid[i][j] = '0'; //将当前点标为已搜
eraseIslands(grid, i - 1, j); //分别搜上下左右点
eraseIslands(grid, i + 1, j);
eraseIslands(grid, i, j - 1);
eraseIslands(grid, i, j + 1);
}
};
BFS:(队列实现)
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0, offsets[] = {0, 1, 0, -1, 0};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {//从矩阵的任一点开始搜索
if (grid[i][j] == '1') {
islands++;
grid[i][j] = '0';
queue<pair<int, int>> todo; //用队列存当前点之后的所有点
todo.push({i, j});
while (!todo.empty()) {
pair<int, int> p = todo.front();
todo.pop();
for (int k = 0; k < 4; k++) {
int r = p.first + offsets[k], c = p.second + offsets[k + 1];
if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1') {
grid[r][c] = '0';
todo.push({r, c});//
}
}
}
}
}
}
return islands;
}
};