深度优先搜索:
用 record 记录数量
两层 for 循环开始遍历
找到一个为 1 的值后,将 record 加 1,并将对当前值进行深度优先搜索,
将周围所有为 1 的值全部置为 0。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int rows = grid.size();
int cols = grid[0].size();
int record = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == '1') {
++record;
dfs(grid, rows, cols, i, j);
}
}
}
return record;
}
void dfs(vector<vector<char>>& grid, int rows, int cols, int i, int j) {
grid[i][j] = '0';
if (i + 1 < rows && grid[i + 1][j] == '1') dfs(grid, rows, cols, i + 1, j);
if (i - 1 >= 0 && grid[i - 1][j] == '1') dfs(grid, rows, cols, i - 1, j);
if (j - 1 >= 0 && grid[i][j - 1] == '1') dfs(grid, rows, cols, i, j - 1);
if (j + 1 < cols && grid[i][j + 1] == '1') dfs(grid, rows, cols, i, j + 1);
}
};
广度优先搜索:
用 record 记录数量
两层 for 循环开始遍历
找到一个为 1 的值后,将 record 加 1,并将当前值加入队列进行广度优先搜索,
要在入队前将值置为 0,否则会围绕一个点产生无限循环
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int rows = grid.size();
int cols = grid[0].size();
int record = 0;
std::queue<std::pair<int, int>> qpair;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == '1') {
qpair.push({i, j});
grid[i][j] = '0';
++record;
while (!qpair.empty()) {
int row = qpair.front().first;
int col = qpair.front().second;
qpair.pop();
if (row + 1 < rows && grid[row + 1][col] == '1') {
grid[row + 1][col] = '0';
qpair.push({row + 1, col});
}
if (row - 1 >= 0 && grid[row - 1][col] == '1') {
grid[row - 1][col] = '0';
qpair.push({row - 1, col});
}
if (col - 1 >= 0 && grid[row][col - 1] == '1') {
grid[row][col - 1] = '0';
qpair.push({row, col - 1});
}
if (col + 1 < cols && grid[row][col + 1] == '1') {
grid[row][col + 1] = '0';
qpair.push({row, col + 1});
}
}
}
}
}
return record;
}
};
并查集: