给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000输出: 1
示例 2:输入:
11000
11000
00100
00011输出: 3
#include <iostream>
#include <vector>
using namespace std;
void dfs(vector<vector<char>> &grid, int i, int j){
int row = grid.size();
int col = grid[0].size();
grid[i][j] = '0';
if (i - 1 >= 0 && grid[i - 1][j] == '1') {
dfs(grid, i - 1, j);
}
if (i + 1 < row && grid[i + 1][j] == '1') {
dfs(grid, i + 1, j);
}
if (j - 1 >= 0 && grid[i][j - 1] == '1') {
dfs(grid, i, j - 1);
}
if (j + 1 < col && grid[i][j + 1] == '1') {
dfs(grid, i, j + 1);
}
}
int numIslands(vector<vector<char>>& grid) {
if (grid.empty()) {
return 0;
}
int row = grid.size();
int col = grid[0].size();
int cnt = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
cnt++;
}
}
}
return cnt;
}
int main() {
vector<vector<char>> grid = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};
int cnt = numIslands(grid);
cout << cnt << endl;
}