作者: 负雪明烛
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. Vue.js知识点总结

    1. Vue.js简介 1.1 Vue.js简介 1.2 创建一个vue实例 2. Vue.js基础 2.1 模板语法 2.2 环境搭建 2.3 生命周期钩子

  2. Oracle数据库导入与导出方法简述

    说明: 1.数据库数据导入导出方法有多种,可以通过exp/imp命令导入导出,也可以用第三方工具导出,如:PLSQL 2.如果熟悉命令,建议用exp/imp命令导入导出,避免第三方工具版本差异引起的问 ...

  3. Linux学习 - Bash变量

    一.用户自定义变量(本地名) 用户自定义变量只有在当前的shell中生效 1 定义变量 name="zheng huiwei" aa=123 2 变量叠加 aa="$aa ...

  4. sonic 安装记录

    https://github.com/valeriansaliou/sonic $ rustc --versionrustc 1.50.0-dev ubantu环境 rocksdb 安装依赖 apt ...

  5. OC-copy,单例

    总结 编号 主题 内容 一 NSFileManager NSFileManager介绍/用法(常见的判断)/文件访问/文件操作 二 集合对象的内存管理 集合对象的内存管理/内存管理总结 三 *copy ...

  6. linux-源码软件管理-yum配置

    总结如下:1.源码配置软件管理2.配置yum本地源和网络源及yum 工作原理讲解3.计算机硬盘介绍 1.1 源码管理软件 压缩包管理命令: # 主流的压缩格式包括tar.rar.zip.war.gzi ...

  7. BS版本的TCP程序

    // 使用Socket对象中的方法getInputStream,获取到网络字节输入流InputStream对象 InputStream is = socket.getInputStream();// ...

  8. for循环中的变量泄漏

    经典的案例 let arr = [] for(var i =0;i<=5;i++){ arr[i]= function fn(){ console.log(i) } } arr[0]() //6 ...

  9. react功能实现-组件创建

    这里主要从两个角度来分析创建一个组件需要怎么做,一个是元素,一个是数据.整理向,大量借鉴,非原创. 1.渲染组件. 我们先明确一点,所有的元素都必须通过render方法来输出渲染.所有,每个组件类最终 ...

  10. 20个ios登陆界面

    原文:http://favbulous.com/post/1001/24-unique-ios-login-screen-showcase Eeve Evernote Food Recood Hips ...