当前位置:网站首页>leetcode: 200. 岛屿数量
leetcode: 200. 岛屿数量
2022-08-02 10:24:00 【uncle_ll】
200. 岛屿数量
来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/number-of-islands/
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'
解法
总的思想是进行遍历,如果遍历到陆地,岛屿数+1,并改变该岛屿的值为‘0’或者设置访问状态为已访问,再基于该陆地,向四周进行扩散,将与之相岭的陆地设置为‘0’或者设置访问状态为已访问
- BFS:用队列进行存储该陆地,并进行四个方向的遍历,如果后续有陆地,进入队列,直到队列为空
- DFS: 用递归的方式进行四个方向的遍历
代码实现
BFS
python实现
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid or len(grid[0]) == 0:
return 0
rows = len(grid)
cols = len(grid[0])
count = 0
dr = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for x in range(rows):
for y in range(cols):
if grid[x][y] == '1':
count += 1
queue = [(x, y)]
grid[x][y] = 0
while queue:
cx, cy = queue.pop(0)
for dx, dy in dr:
nx = cx + dx
ny = cy + dy
if 0<= nx < rows and 0 <= ny < cols and grid[nx][ny] == '1':
queue.append((nx, ny))
grid[nx][ny] = '0'
return count
c++实现
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int rows = grid.size();
if (rows == 0)
return 0;
int cols = grid[0].size();
if (cols == 0)
return 0;
vector<pair<int, int>> dr;
dr = {
{
1, 0}, {
-1, 0}, {
0, 1}, {
0, -1}};
int count = 0;
for (int i=0; i< rows; i++) {
for (int j=0; j< cols; j++) {
if (grid[i][j] == '1') {
count++;
grid[i][j] = 0;
queue<pair<int, int>> q;
q.push({
i, j});
while (!q.empty()) {
auto cur = q.front();
q.pop();
int x = cur.first;
int y = cur.second;
for (auto d: dr) {
int dx = d.first;
int dy = d.second;
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && grid[nx][ny] == '1'){
q.push({
nx, ny});
grid[nx][ny] = '0';
}
}
}
}
}
}
return count;
}
};
复杂度分析
- 时间复杂度: O ( M N ) O(MN) O(MN) M和N分别为行数和列数
- 空间复杂度: O ( m i n ( M , N ) ) O(min(M, N)) O(min(M,N)) 在最坏情况下,整个网格均为陆地,队列的大小可以达到 min ( M , N ) \min(M, N) min(M,N)。
DFS
python实现
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid or len(grid[0]) == 0:
return 0
rows = len(grid)
cols = len(grid[0])
count = 0
dr = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for x in range(rows):
for y in range(cols):
if grid[x][y] == '1':
count += 1
queue = [(x, y)]
grid[x][y] = 0
while queue:
cx, cy = queue.pop(0)
for dx, dy in dr:
nx = cx + dx
ny = cy + dy
if 0<= nx < rows and 0 <= ny < cols and grid[nx][ny] == '1':
queue.append((nx, ny))
grid[nx][ny] = '0'
return count
c++实现
class Solution {
private:
void dfs(vector<vector<char>>& grid, int r, int c) {
int nr = grid.size();
int nc = grid[0].size();
grid[r][c] = '0';
if (r - 1 >= 0 && grid[r-1][c] == '1') dfs(grid, r - 1, c);
if (r + 1 < nr && grid[r+1][c] == '1') dfs(grid, r + 1, c);
if (c - 1 >= 0 && grid[r][c-1] == '1') dfs(grid, r, c - 1);
if (c + 1 < nc && grid[r][c+1] == '1') dfs(grid, r, c + 1);
}
public:
int numIslands(vector<vector<char>>& grid) {
int nr = grid.size();
if (!nr) return 0;
int nc = grid[0].size();
int num_islands = 0;
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
++num_islands;
dfs(grid, r, c);
}
}
}
return num_islands;
}
};
复杂度分析
- 时间复杂度: O ( M N ) O(MN) O(MN) M和N分别为行数和列数
- 空间复杂度: O ( M N ) O(MN) O(MN) M和N分别为行数和列数
参考
边栏推荐
- 软件测试岗位巨坑?阿里在职7年测试人告诉你千万别上当
- 软件测试的基本理论知识(软件测试面试基础知识)
- The realization of the list
- Hongxing, donate another million
- R language time series data arithmetic operation: use the log function to log the time series data, and use the diff function to calculate the successive difference of the logarithmic time series data
- 身为程序猿——谷歌浏览器的这些骚操作你真的废吗!【熬夜整理&建议收藏】[通俗易懂]
- Oracle超全SQL,细节狂魔
- 多大数量级会出现哈希碰撞
- 牛客刷题——剑指offer(第三期)
- 博云入选Gartner中国DevOps代表厂商
猜你喜欢
5G基础学习1、5G网络架构、网络接口及协议栈
You Only Hypothesize Once: 用旋转等变描述子估计变换做点云配准(已开源)
yolov7创新点
How to choose a truly "easy-to-use, high-performance" remote control software
npm ERR! 400 Bad Request - PUT xxx - Cannot publish over previously published version “1.0.0“.
多大数量级会出现哈希碰撞
The realization of the list
After 21 years of graduation, I switched to software testing. From 0 income to a monthly salary of over 10,000, I am really lucky...
The heavyweights are coming!Spoilers for the highlights of the Alibaba Cloud Life Science and Intelligent Computing Summit
MySql千万级分页优化,快速插入千万数据方法
随机推荐
DVWA Clearance Log 2 - Command Injection
Linux系统卸载,安装,升级,迁移clickHouse数据库
LayaBox---TypeScript---迭代器和生成器
【术语科普】关于集成工作台那些难懂的词儿,看这篇秒懂!
Mysql环境变量的配置(详细图解)
FPGA手撕代码——CRC校验码的多种Verilog实现方式 (2021乐鑫科技数字IC提前批代码编程)
WPF 截图控件之文字(七)「仿微信」
LayaBox---TypeScript---三斜线指令
行为型模式-模板方法模式
R language ggplot2 visualization: use the ggbarplot function of the ggpubr package to visualize the stacked bar plot, the lab.pos parameter specifies the position of the numerical label of the bar cha
How to encapsulate the wx.request() request of WeChat applet
R language ggplot2 visualization: based on the fill parameter and shape parameter in the aes function, custom draw a grouped line chart and add data points (scatter points), use the legend.position fu
WPF 截图控件之文字(七)「仿微信」
iNFTnews | 看见元宇宙的两面,何谓全真互联网和价值互联网?
链表的实现
qq邮箱日发5万邮件群发技术(qq邮箱怎样定时发送邮件)
R语言ggplot2可视化:使用ggpubr包的ggtexttable函数可视化表格数据(直接绘制表格图或者在图像中添加表格数据)、使用tbody_add_border为表格中的表头添加外侧框线
Linux system uninstall, install, upgrade, migrate clickHouse database
身为程序猿——谷歌浏览器的这些骚操作你真的废吗!【熬夜整理&建议收藏】[通俗易懂]
如何封装微信小程序的 wx.request() 请求