当前位置:网站首页>leetcode: 200. Number of islands
leetcode: 200. Number of islands
2022-08-02 11:00: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'
解法
The general idea is to traverse,如果遍历到陆地,岛屿数+1,and change the value of the island to ‘0’Or set the access status to Accessed,based on the land,Spread around,Set the land with the ridge to ‘0’Or set the access status to Accessed
- BFS:The land is stored with a queue,And traverse in four directions,If there is land in the future,进入队列,直到队列为空
- DFS: Traverse in four directions recursively
代码实现
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分别为行数和列数
参考
边栏推荐
- 利用二维数据学习纹理三维网格生成(CVPR 2020)
- 多线程(基础) - 4万字总结
- 21 Days Learning Challenge - Day 1 Punch (Screen Density)
- 循环结构--while循环
- Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
- leetcode: 200. 岛屿数量
- 21年毕业转行软件测试,从0收入到月薪过万,我真的很幸运...
- mysql清除binlog日志文件
- FPGA手撕代码——CRC校验码的多种Verilog实现方式 (2021乐鑫科技数字IC提前批代码编程)
- 小几届的学弟问我,软件测试岗是选11k的华为还是20k的小公司,我直呼受不了,太凡尔赛了~
猜你喜欢

MySql模糊查询大全

软件工程国考总结——选择题

4年手工测试被应届生取代了,用血与泪的教训给xdm一个忠告,该学自动化了...

OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)

10份重磅报告 — 展望中国数字经济未来

You Only Hypothesize Once: 用旋转等变描述子估计变换做点云配准(已开源)

图形处理单元(GPU)的演进

21年毕业转行软件测试,从0收入到月薪过万,我真的很幸运...

5G基础学习1、5G网络架构、网络接口及协议栈

Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)
随机推荐
4年手工测试被应届生取代了,用血与泪的教训给xdm一个忠告,该学自动化了...
C#/VB.NET 添加多行多列图片水印到Word文档
爆款视频怎么做?这里或许有答案!
MySQL模糊查询性能优化
突破边界,华为存储的破壁之旅
The sitcom "Re-Walking the Long March" was staged
ssm网页访问数据库数据报错
多线程之生产者与消费者
The 38-year-old daughter is not in love and has no stable job, the old mother is crying
Com多进程通信实现
LayaBox---TypeScript---JSX
从零开始Blazor Server(5)--权限验证
LayaBox---TypeScript---模块
Jay Chou's new song is released, crawl the "Mojito" MV barrage, and see what the fans have to say!
只问耕耘,不问收获,其实收获却在耕耘中
如何在技术上来保证LED显示屏质量?
mysql清除binlog日志文件
find查找多类型结尾文件
Three.JS程序化建模入门
字母交换--字符串dp