LeetCode知识点总结 - 934

LeetCode 934. Shortest Bridge

考点难度
MatrixMedium
题目

You are given an n x n binary matrix grid where 1 represents land and 0 represents water.

An island is a 4-directionally connected group of 1’s not connected to any other 1’s. There are exactly two islands in grid.

You may change 0’s to 1’s to connect the two islands to form one island.

Return the smallest number of 0’s you must flip to connect the two islands.

思路

1 先用dfs找出第一个island的所有坐标,保存到stack里
2 对于stack里的每个坐标,检查它的四个方向有没有1,如果找到1返回step = 1,如果没有就把这个坐标对应的值改掉,并且储存到一个新的list里(不是原来的stack)
3 当原来的stack全部被iterate完但是没有找到1,step + 1,iterate这个循环里create的新的list
4 以此类推直到找到1

答案
class Solution:
    def shortestBridge(self, A: List[List[int]]) -> int:
        
        found = False
        stack = []
        n, m = len(A), len(A[0])
        # find the first island
        for i in range(n):
            for j in range(m):
                if A[i][j]:
                    # using depth first search to find all connected ('1') locations
                    # since there are only two islands
                    # we only need to find the first one 
                    self.dfs(A, i, j, n, m, stack)
                    found = True
                    break
            if found:
                break

        steps = 0
        # breadth first search, once we find next '1', that is our final answer
        dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        while stack:
            size = len(stack)
            level = []
            while(size):
                temp = stack.pop()
                size-=1
                x, y = temp[0], temp[1]
                for dx, dy in dirs:
                    tx = x+dx
                    ty = y+dy
                    if tx<0 or ty<0 or tx>=n or ty>=m or A[tx][ty]==2:
                        continue
                    if A[tx][ty]==1:
                        return steps
                    A[tx][ty]=2
                    level.append((tx, ty))
            steps+=1
            stack = level
        return -1 
                
    def dfs(self, A, row, col, n, m, stack):
        # we only need to find connected '1's
        # we need A[row][col]==1\
        if row<0 or col<0 or row>=n or col>=m or A[row][col]!=1:
            return 
        A[row][col]=2
        # use stack for breath first search
        stack.append((row, col))
        self.dfs(A, row+1, col, n, m, stack)
        self.dfs(A, row-1, col, n, m, stack)
        self.dfs(A, row, col+1, n, m, stack)
        self.dfs(A, row, col-1, n, m, stack)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值