前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 1905. Count Sub Islands

Leetcode 1905. Count Sub Islands

作者头像
Tyan
发布2021-08-13 11:56:07
4070
发布2021-08-13 11:56:07
举报
文章被收录于专栏:SnailTyanSnailTyan

1. Description

Count Sub Islands
Count Sub Islands

2. Solution

**解析:**Version 1,以第二个矩阵中碰到的1作为起点,然后使用广度优先搜索找到所有相邻的1,即一个岛屿,并将所有岛的坐标保存到队列中(值为1的坐标),将矩阵二中搜索的点对应的值设为2,防止重复搜索,搜索过程中需要同时检查搜索的点是否是矩阵一种的岛屿,如果不是,将标志位设为False,最后根据标志位判断是否是矩阵一种的子岛屿。搜索过程其实就是Flood Fill算法。

  • Version 1
代码语言:javascript
复制
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/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-08-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档