当前位置:网站首页>【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
边栏推荐
猜你喜欢
Redux——详解
Storage read-write speed and network measurement based on rz/g2l | ok-g2ld-c development board
Steps for Navicat to create a new database
LeetCode刷题——奇偶链表#328#Medium
10_ Redis_ geospatial_ command
. Net again! Happy 20th birthday
Custom exception
Bing. Com website
How to intercept the value of a key from the JSON string returned by wechat?
Let your HMI have more advantages. Fet-g2ld-c core board is a good choice
随机推荐
LeetCode刷题——奇偶链表#328#Medium
Libcurl Lesson 13 static library introduces OpenSSL compilation dependency
终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)
Practice of compiling principle course -- implementing an interpreter or compiler of elementary function operation language
. Net again! Happy 20th birthday
How to solve the problem of database content output
07_ Hash
Application of CDN in game field
folium,确诊和密接轨迹上图
党史纪实主题公益数字文创产品正式上线
Data analysis thinking analysis methods and business knowledge - business indicators
17_Redis_Redis发布订阅
21_Redis_浅析Redis缓存穿透和雪崩
How to test tidb with sysbench
MySQL calculate n-day retention rate
Set set you don't know
14_ Redis_ Optimistic lock
你不知道的Set集合
2022 college students in Liaoning Province mathematical modeling a, B, C questions (related papers and model program code online disk download)
搭建自己的语义分割平台deeplabV3+