LeetCode-200. Number of Islands

阅读 68

2022-08-10


Given a 2d grid map of ​​'1'​​​s (land) and ​​'0'​​s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

题解:

标准dfs

class Solution {
public:
void dfs(vector<vector<char>>& grid, int x, int y, int n, int m) {
if (x >= n || x < 0 || y >= m || y < 0) {
return;
}
if (grid[x][y] == '1') {
grid[x][y] = '0';
dfs(grid, x, y - 1, n, m);
dfs(grid, x + 1, y, n, m);
dfs(grid, x, y + 1, n, m);
dfs(grid, x - 1, y, n, m);
}
}
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() == true) {
return 0;
}
int res = 0;
int n = grid.size(), m = grid[0].size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j, n, m);
res++;
}
}
}
return res;
}
};

 

精彩评论(0)

0 0 举报