LeetCode-200. Number of Islands

网友投稿 575 2022-11-09

LeetCode-200. Number of Islands

LeetCode-200. Number of Islands

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:11110110101100000000Output: 1

Example 2:

Input:11000110000010000011Output: 3

题解:

标准dfs

class Solution {public: void dfs(vector>& 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>& 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; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-139. Word Break
下一篇:LeetCode-215. Kth Largest Element in an Array
相关文章

 发表评论

暂时没有评论,来抢沙发吧~