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

Leetcode 934. Shortest Bridge

作者头像
Tyan
发布2021-08-10 10:44:34
3670
发布2021-08-10 10:44:34
举报
文章被收录于专栏:SnailTyanSnailTyan

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

Shortest Bridge
Shortest Bridge

2. Solution

**解析:**Version 1,先找到矩阵中第一个1作为起点,然后使用广度优先搜索找到所有相邻的1,即第一个岛,并将所有岛的坐标及更改的0计数保存到队列中,初始计数为0,搜索第一个岛的同时,将各个点对应的值设为2,防止重复搜索。从第一个岛的所有点开始,重新使用广度优先搜索,如果搜索的点值为0,将值设为2,表示已经搜索过,同时将点的坐标及计数保存,计数要加1,如果搜索的点为1,说明找到了第二个岛,返回反转的0的计数。

  • Version 1
代码语言:javascript
复制
class Solution:
    def shortestBridge(self, grid: List[List[int]]) -> int:
        n = len(grid)
        queue = collections.deque()
        queue2 = collections.deque()
        for i in range(n):
            flag = False
            for j in range(n):
                if grid[i][j] == 1:
                    grid[i][j] = 2
                    queue.append((i, j))
                    flag = True
                    break
            if flag:
                break
        while queue:
            x, y = queue.popleft()
            queue2.append((x, y, 0))
            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 < n-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))
        while queue2:
            x, y, count = queue2.popleft()
            if x > 0:
                if grid[x-1][y] == 0:
                    grid[x-1][y] = 2
                    queue2.append((x-1, y, count + 1))
                elif grid[x-1][y] == 1:
                    return count
            if y > 0:
                if grid[x][y-1] == 0:
                    grid[x][y-1] = 2
                    queue2.append((x, y-1, count + 1))
                elif grid[x][y-1] == 1:
                    return count
            if x < n-1:
                if grid[x+1][y] == 0:
                    grid[x+1][y] = 2
                    queue2.append((x+1, y, count + 1))
                elif grid[x+1][y] == 1:
                    return count
            if y < n-1:
                if grid[x][y+1] == 0:
                    grid[x][y+1] = 2
                    queue2.append((x, y+1, count + 1))
                elif grid[x][y+1] == 1:
                    return count

Reference

  1. https://leetcode.com/problems/shortest-bridge/
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/08/06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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