当前位置:网站首页>【LeetCode】1905-统计子岛屿
【LeetCode】1905-统计子岛屿
2022-07-02 12:09:00 【酥酥~】
给你两个 m x n 的二进制矩阵 grid1 和 grid2 ,它们只包含 0 (表示水域)和 1 (表示陆地)。一个 岛屿 是由 四个方向 (水平或者竖直)上相邻的 1 组成的区域。任何矩阵以外的区域都视为水域。
如果 grid2 的一个岛屿,被 grid1 的一个岛屿 完全 包含,也就是说 grid2 中该岛屿的每一个格子都被 grid1 中同一个岛屿完全包含,那么我们称 grid2 中的这个岛屿为 子岛屿 。
请你返回 grid2 中 子岛屿 的 数目 。
示例 1:
输入: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
输出: 3
解释: 如上图所示,左边为 grid1 ,右边为 grid2 。
grid2 中标红的 1 区域是子岛屿,总共有 3 个子岛屿。
示例 2:
**输入:**grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
**输出:**2
**解释:**如上图所示,左边为 grid1 ,右边为 grid2 。
grid2 中标红的 1 区域是子岛屿,总共有 2 个子岛屿。
提示:
- m == grid1.length == grid2.length
- n == grid1[i].length == grid2[i].length
- 1 <= m, n <= 500
- grid1[i][j] 和 grid2[i][j] 都要么是 0 要么是 1 。
#广度优先遍历
class Solution(object):
def countSubIslands(self, grid1, grid2):
m = len(grid2)
n = len(grid2[0])
result = 0#统计子岛屿数量
for i in range(m):
for j in range(n):
if grid2[i][j] == 1:
queue = []
grid2[i][j] = 0
queue.append((i,j))
flag = 1#标志是否为子岛屿
while queue:
x,y = queue[0]
queue.pop(0)
if grid1[x][y] == 0:#如果在grid1中对应的位置为海洋,则该岛屿不是子岛屿
flag = 0
for xx,yy in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if 0<=xx<m and 0<=yy<n and grid2[xx][yy]==1:
grid2[xx][yy] = 0
queue.append((xx,yy))
result += flag
return result
#深度优先遍历
class Solution(object):
def countSubIslands(self, grid1, grid2):
m = len(grid2)
n = len(grid2[0])
result = 0
for i in range(m):
for j in range(n):
if grid2[i][j] == 1:
stack = []
grid2[i][j] = 0
stack.append((i,j))
flag = 1
while stack:
x,y = stack[-1]
stack.pop()
if grid1[x][y] == 0:
flag = 0
for xx,yy in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:#四个方向遍历
if 0<=xx<m and 0<=yy<n and grid2[xx][yy]==1:
grid2[xx][yy] = 0
stack.append((xx,yy))
result += flag
return result
边栏推荐
- . Solution to the problem of Chinese garbled code when net core reads files
- Summary of the first three passes of sqli Labs
- Solution of Queen n problem
- 03_线性表_链表
- Application of CDN in game field
- 02_ Linear table_ Sequence table
- 面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?
- 语义分割学习笔记(一)
- Yolov5 code reproduction and server operation
- 6.12 critical moment of Unified Process Platform
猜你喜欢
随机推荐
工程师评测 | RK3568开发板上手测试
Facing the challenge of "lack of core", how can Feiling provide a stable and strong guarantee for customers' production capacity?
LeetCode刷题——去除重复字母#316#Medium
搭载TI AM62x处理器,飞凌FET6254-C核心板首发上市!
02_线性表_顺序表
Kibana basic operation
高考录取分数线爬取
16_ Redis_ Redis persistence
02_ Linear table_ Sequence table
自定义异常
终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)
Build your own semantic segmentation platform deeplabv3+
搭建自己的语义分割平台deeplabV3+
13_ Redis_ affair
11_ Redis_ Hyperloglog_ command
夏季高考文化成绩一分一段表
LeetCode刷题——递增的三元子序列#334#Medium
FPGA - 7系列 FPGA内部结构之Clocking -03- 时钟管理模块(CMT)
03.golang初步使用
How to write sensor data into computer database