美文网首页Leetcode
Leetcode 1905. Count Sub Islands

Leetcode 1905. Count Sub Islands

作者: SnailTyan | 来源:发表于2021-09-13 08:27 被阅读0次

    文章作者: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/

    相关文章

      网友评论

        本文标题:Leetcode 1905. Count Sub Islands

        本文链接:https://www.haomeiwen.com/subject/vdecbltx.html