Leetcode 1905. Count Sub Islands
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
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 = 0queue = 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 countdef subIslands(self, queue, grid, check):m = len(grid)n = len(grid[0])flag = Truewhile queue:x, y = queue.popleft()if check[x][y] == 0:flag = Falseif x > 0 and grid[x-1][y] == 1:grid[x-1][y] = 2queue.append((x-1, y))if y > 0 and grid[x][y-1] == 1:grid[x][y-1] = 2queue.append((x, y-1))if x < m-1 and grid[x+1][y] == 1:grid[x+1][y] = 2queue.append((x+1, y))if y < n-1 and grid[x][y+1] == 1:grid[x][y+1] = 2queue.append((x, y+1)) if flag:return 1else:return 0
Reference
- https://leetcode.com/problems/count-sub-islands/
Leetcode 1905. Count Sub Islands相关推荐
- Leetcode 1905. Count Sub Islands [Python]
看上去用BFS最简单,但是BFS会TLE,且卡住的TC在17,可能逻辑上还是有错,但是不好确定.先留下吧. 第二种方式用DFS, 把grid2中为1而对位grid1中为0的位置提出,开始DFS,因为这 ...
- 【Leetcode】1905. Count Sub Islands
题目地址: https://leetcode.com/problems/count-sub-islands/ 给定两个m×nm\times nm×n的0−10-10−1矩阵AAA和BBB,111代表陆 ...
- LeetCode 1905. 统计子岛屿
LeetCode 1905. 统计子岛屿 题目 思路 代码 题目 链接: https://leetcode.cn/problems/count-sub-islands/ 给你两个 m x n 的二进制 ...
- LeetCode 38. Count and Say
问题链接 LeetCode 38. Count and Say 题目解析 找规律,每一个数字串是上一个数字串的"读法".比如:n=1时为"1",读作" ...
- 【Hard 递归 动态规划 回文串15】LeetCode 730. Count Different Palindromic Subsequences
LeetCode 730. Count Different Palindromic Subsequences 博客转载自:http://zxi.mytechroad.com/blog/dynamic- ...
- [勇者闯LeetCode] 38. Count and Say
[勇者闯LeetCode] 38. Count and Say Description The count-and-say sequence is the sequence of integers b ...
- 【Leetcode】Number of Islands
题目链接:https://leetcode.com/problems/number-of-islands/ 题目: Given a 2d grid map of '1's (land) and '0' ...
- LeetCode 204. Count Primes--从一开始的质数个数--Python解法--面试算法题
题目地址:Count Primes - LeetCode Count the number of prime numbers less than a non-negative number, n. E ...
- LeetCode 250. Count Univalue Subtrees
原题链接在这里:https://leetcode.com/problems/count-univalue-subtrees/ 题目: Given a binary tree, count the nu ...
最新文章
- struts2请求处理过程源代码分析(1)
- DynamicProgramming动态规划整理
- 选择适合过一辈子的人
- 设计模式之创建型模式
- 洛谷 1281 书的复制
- delphi使用sqlite数据库时的中文路径问题
- 01-How to setup SDK and compile TAs
- Delta3d插件机制
- .NET 4.0 调用 C dll 触发 AccessViolationException 异常的处理方案
- EfficientDet:COCO 51.0 mAP!谷歌大脑提出目标检测新标杆
- Spring Boot这只怪物到底是如何跑起来的?
- hihocoder第196周
- 20210924 python 技术点
- Python系列之Python-docx生成运行日报Word模板
- 《彩虹屁》快夸夸我!彩虹屁生成器
- 基于bind搭建智能dns
- MuseScore入门教程(二、添加基本音乐符号)
- Tomcat 自动部署、回滚(java project)脚本
- 数据分析漏斗模型浅谈
- 天梯赛L1(1-80)