https://leetcode.com/problems/shortest-bridge/description/

1) 코드
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
n = len(grid)
sx = -1
sy = -1
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
sx = i
sy = j
stk = []
stk.append([sx, sy])
visited = set()
while stk:
x, y = stk.pop()
visited.add((x, y))
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<=nx and nx<n and 0<=ny and ny<n and grid[nx][ny] and (nx,ny) not in visited:
stk.append([nx, ny])
visited.add((nx,ny))
queue = list(visited)
ans = 0
while queue:
next_queue = []
for x, y in queue:
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<=nx and nx<n and 0<=ny and ny<n and (nx,ny) not in visited:
if grid[nx][ny] == 1:
return ans
next_queue.append([nx,ny])
visited.add((nx,ny))
queue = next_queue
ans += 1
2) 해설