作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/shortest-bridge/description/

题目描述

In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.)

Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.

Return the smallest number of 0s that must be flipped. (It is guaranteed that the answer is at least 1.)

Example 1:

Input: [[0,1],[1,0]]
Output: 1

Example 2:

Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2

Example 3:

Input: [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1

Note:

  1. 1 <= A.length = A[0].length <= 100
  2. A[i][j] == 0 or A[i][j] == 1

题目大意

题目给出一个二维矩阵,其中的0表示水,1表示陆地,四联通的陆地会连成一片岛。题目保证给出了两个岛,求两个岛之间的最短路径。

解题方法

DFS + BFS

本周周赛第三题,比赛的时候没时间写了,但是赛后感觉这个题很简单。

首先用DFS来确定其中一个岛,把这个岛所有的1变成了2,这么做的目的是和另一个岛作为区分。需要注意的是把找到的这个岛的每个位置都添加到队列里面,我们会用这个队列去做BFS.

找出了岛之后,使用BFS,来找出这个岛离1最近的距离是多少。每次循环是相当于走了一步,把所有走了一步仍然是水路的位置设置成2,并放到队列里;如果找到了1,就可以直接结束了,因为我们的BFS没走一步会向前走一些,第一次寻找到的就是最近的距离;如果找到的是2,那说明这个位置已经遍历过了,直接不要管了。

最坏时间复杂度是O(MN),最坏空间复杂度O(MN). 时间是240 ms。

class Solution:
def shortestBridge(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
M, N = len(A), len(A[0])
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
visited = [[0] * N for _ in range(M)]
hasfind = False
que = collections.deque()
for i in range(M):
if hasfind: break
for j in range(N):
if A[i][j] == 1:
self.dfs(A, i, j, visited, que)
hasfind = True
break
step = 0
while que:
size = len(que)
for _ in range(size):
i, j = que.popleft()
for d in dirs:
x, y = i + d[0], j + d[1]
if 0 <= x < M and 0 <= y < N:
visited[x][y] = 1
if A[x][y] == 1:
return step
elif A[x][y] == 0:
A[x][y] = 2
que.append((x, y))
else:
continue
step += 1
return -1 def dfs(self, A, i, j, visited, que):
if visited[i][j]: return
visited[i][j] = 1
M, N = len(A), len(A[0])
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
if A[i][j] == 1:
que.append((i, j))
A[i][j] = 2
for d in dirs:
x, y = i + d[0], j + d[1]
if 0 <= x < M and 0 <= y < N:
self.dfs(A, x, y, visited, que)

相似题目

参考资料

日期

2018 年 11 月 4 日 —— 下雨的周日

【LeetCode】934. Shortest Bridge 解题报告(Python)的更多相关文章

  1. [LeetCode] 934. Shortest Bridge 最短的桥梁

    In a given 2D binary array A, there are two islands.  (An island is a 4-directionally connected grou ...

  2. LeetCode 934. Shortest Bridge

    原题链接在这里:https://leetcode.com/problems/shortest-bridge/ 题目: In a given 2D binary array A, there are t ...

  3. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  4. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  5. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  6. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  7. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  8. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  9. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

随机推荐

  1. Pysam 处理bam文件

    Pysam可用来处理bam文件 安装: 用 pip 或者 conda即可 使用: Pysam的函数有很多,主要的读取函数有: AlignmentFile:读取BAM/CRAM/SAM文件 Varian ...

  2. Pycharm的简单配置和使用

    外观 Ctrl+滚轮改变字体大小:file -> Setting ->Editor-〉General -> Mouse: 字体.颜色:file->settings->Ed ...

  3. R语言与医学统计图形-【21】ggplot2标题

    ggplot2绘图系统--标题 在期刊杂志中,需要设置的图形标题并不多. 除了图形标题,还有坐标轴标题(标签).图例标题.脚注等. 标题函数:ggtitle,labs 坐标轴标题函数:xlab,yla ...

  4. 分布式事务(4)---最终一致性方案之TCC

    分布式事务(1)-理论基础 分布式事务(2)---强一致性分布式事务解决方案 分布式事务(3)---强一致性分布式事务Atomikos实战 强一致性分布式事务解决方案要求参与事务的各个节点的数据时刻保 ...

  5. github小白的记录随笔

    此文章是基础本地安装好了git环境的新手小白. 进入您要上传项目的根路径,右键选择Git Bash Here. 输入命令: git init //初始化git仓库环境 git remote add o ...

  6. A Child's History of England.12

    Dunstan, Abbot of Glastonbury Abbey, was one of the most sagacious of these monks. He was an ingenio ...

  7. Activity 详解

    1.活动的生命周期 1.1.返回栈 Android是使用任务(Task)来管理活动的,一个任务就是一组存放在栈里的活动的集合,这个栈也被称作返回栈.栈是一种先进后出的数据结构,在默认情况下,每当我们启 ...

  8. zabbix之监控面试

    先用shell脚本把值取出来,然后重启agent,在server端用zabbix-get命令测试一下,看能不能通过userparameter指定的可以将值取出来,如果没问题,在在网页创建模板,加监控项 ...

  9. springboot+vue集成mavon-editor,开发在线文档知识库

    先睹为快,来看下效果: 技术选型 SpringBoot.Spring Security.Oauth2.Vue-element-admin 集成mavon-editor编辑器 安装 mavon-edit ...

  10. IDEA 使用rest client测试

    一.进入 rest 控制台 idea 导航栏 ==> Tools ==> HTTP Client ==> Test RESTFUL Web Service 如图: 一般来说,idea ...