200.岛屿数量 (Medium)*
题目描述*
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例*
输入:
11110
11010
11000
00000
输出: 1
输入:
11000
11000
00100
00011
输出: 3
代码*
dfs 或 bfs 即可。还可以用并查集,过段时间学一下。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int cnt = 0;
int rows = grid.size();
if(rows == 0) {
return 0;
}
int cols = grid[0].size();
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(grid[i][j] == '1') {
dfs(grid, i, j);
cnt++;
}
}
}
return cnt;
}
void dfs(vector<vector<char>>& grid, int i, int j) {
if(i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() || grid[i][j] != '1') {
return;
}
grid[i][j] = '2';
dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}
};
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int cnt = 0;
int rows = grid.size();
if(rows == 0) {
return 0;
}
int cols = grid[0].size();
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(grid[i][j] == '1') {
bfs(grid, i, j, rows, cols);
cnt++;
}
}
}
return cnt;
}
void bfs(vector<vector<char>>& grid, int i, int j, int rows, int cols) {
queue<int> helpQueue;
helpQueue.push(i * cols + j);
while(!helpQueue.empty()) {
int cur = helpQueue.front();
helpQueue.pop();
int row = cur / cols;
int col = cur % cols;
if(grid[row][col] == '2') {
continue;
}
grid[row][col] = '2';
if(row != rows - 1 && grid[row + 1][col] == '1') {
helpQueue.push((row + 1) * cols + col);
}
if(col != cols - 1 && grid[row][col + 1] == '1') {
helpQueue.push(row * cols + col + 1);
}
if(row != 0 && grid[row - 1][col] == '1') {
helpQueue.push((row - 1) * cols + col);
}
if(col != 0 && grid[row][col - 1] == '1') {
helpQueue.push(row * cols + col - 1);
}
}
}
};
最后更新: July 23, 2022