文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Count Sub Islands2. Solution
解析:Version 1,以第二个矩阵中碰到的1
作为起点,然后使用广度优先搜索找到所有相邻的1
,即一个岛屿,并将所有岛的坐标保存到队列中(值为1的坐标),将矩阵二中搜索的点对应的值设为2
,防止重复搜索,搜索过程中需要同时检查搜索的点是否是矩阵一种的岛屿,如果不是,将标志位设为False
,最后根据标志位判断是否是矩阵一种的子岛屿。搜索过程其实就是Flood Fill算法。
- Version 1
class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
m = len(grid1)
n = len(grid1[0])
count = 0
queue = collections.deque()
for i in range(m):
for j in range(n):
if grid2[i][j] == 1:
queue.append((i, j))
count += self.subIslands(queue, grid2, grid1)
return count
def subIslands(self, queue, grid, check):
m = len(grid)
n = len(grid[0])
flag = True
while queue:
x, y = queue.popleft()
if check[x][y] == 0:
flag = False
if x > 0 and grid[x-1][y] == 1:
grid[x-1][y] = 2
queue.append((x-1, y))
if y > 0 and grid[x][y-1] == 1:
grid[x][y-1] = 2
queue.append((x, y-1))
if x < m-1 and grid[x+1][y] == 1:
grid[x+1][y] = 2
queue.append((x+1, y))
if y < n-1 and grid[x][y+1] == 1:
grid[x][y+1] = 2
queue.append((x, y+1))
if flag:
return 1
else:
return 0
网友评论