当前位置:网站首页>【LeetCode】200-岛屿数量
【LeetCode】200-岛屿数量
2022-07-02 12:09:00 【酥酥~】
给你一个由 ‘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,不要等着从队列or栈中取出来之后再置为0,会导致大量坐标点被重复入队or入栈,使得时间超出限制!!!
##广度优先遍历
class Solution(object):
def numIslands(self, grid):
n = len(grid)#获取数组长度
if n == 0:
return 0
m = len(grid[0])#获取数组宽度
cnt = 0#岛屿数量
queue = []#队列容器
for i in range(n):
for j in range(m):
if grid[i][j] == "1":#如果遇见陆地就开始遍历
cnt+=1#岛屿数量加一
grid[i][j]="0"#置为0,以免重复访问
queue.append((i,j))#加入队列中,开始遍历
while queue:
x,y = queue[0]
queue.pop(0)
for xx,yy in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:#四个方向遍历
if 0<=xx<n and 0<=yy<m and grid[xx][yy]=="1":
grid[xx][yy]="0"
queue.append((xx,yy))
return cnt
##深度优先遍历
class Solution(object):
def numIslands(self, grid):
n = len(grid)
if n == 0:
return 0
m = len(grid[0])
cnt = 0
stack = []
for i in range(n):
for j in range(m):
if grid[i][j] == "1":
cnt+=1
grid[i][j]="0"
stack.insert(0,(i,j))
while stack:
x,y = stack[0]
stack.pop(0)
for xx,yy in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if 0<=xx<n and 0<=yy<m and grid[xx][yy]=="1":
grid[xx][yy]="0"
stack.insert(0,(xx,yy))
return cnt
边栏推荐
- 面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?
- 你不知道的Set集合
- 基于RZ/G2L | OK-G2LD-C开发板存储读写速度与网络实测
- Libcurl Lesson 13 static library introduces OpenSSL compilation dependency
- 让您的HMI更具优势,FET-G2LD-C核心板是个好选择
- Pytoch saves tensor to Mat file
- folium,确诊和密接轨迹上图
- Topology architecture of the minimum deployment of tidb cluster
- XML Configuration File
- folium地图无法显示的问题,临时性解决方案如下
猜你喜欢
随机推荐
MySQL -- Index Optimization -- order by
03_线性表_链表
Oracle primary key auto increment
Bing.com網站
XML Configuration File
[solution] educational codeforces round 82
I made an istio workshop. This is the first introduction
PTA 天梯赛习题集 L2-001 城市间紧急救援
微信支付宝账户体系和支付接口业务流程
04.进入云原生后的企业级应用构建的一些思考
How to intercept the value of a key from the JSON string returned by wechat?
Summary of the first three passes of sqli Labs
02_线性表_顺序表
Loss function and positive and negative sample allocation: Yolo series
Pytoch saves tensor to Mat file
Download blender on Alibaba cloud image station
2022 年辽宁省大学生数学建模A、B、C题(相关论文及模型程序代码网盘下载)
JVM architecture, classloader, parental delegation mechanism
Map introduction
百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香