Created
May 28, 2023 16:00
-
-
Save Desolve/4499fef61fa66238f3dc5f9bd440a703 to your computer and use it in GitHub Desktop.
0934 Shortest Bridge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def shortestBridge(self, A: List[List[int]]) -> int: | |
r, c = len(A), len(A[0]) | |
start = set() | |
dirs = [(-1, 0), (0, -1), (0, 1), (1, 0)] | |
def dfs(i, j): | |
A[i][j] = 2 | |
for d in dirs: | |
x, y = i + d[0], j + d[1] | |
if 0 <= x < r and 0 <= y < c: | |
if A[x][y] == 1: | |
dfs(x, y) | |
if A[x][y] == 0: | |
start.add((i, j)) | |
def set_l1(): | |
for i in range(r): | |
for j in range(c): | |
if A[i][j] == 1: | |
return dfs(i, j) | |
set_l1() | |
from collections import deque | |
step = 0 | |
q = deque(start) | |
while q: | |
l = len(q) | |
for _ in range(l): | |
i, j = q.popleft() | |
for d in dirs: | |
x, y = i + d[0], j + d[1] | |
if 0 <= x < r and 0 <= y < c: | |
if A[x][y] == 1: | |
return step | |
elif A[x][y] == 0: | |
A[x][y] = -1 | |
q.append((x, y)) | |
step += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment