Leetcode 1905. Count Sub Islands

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Count Sub Islands

2. 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

Reference

  1. https://leetcode.com/problems/count-sub-islands/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值