MediumNo. 0934
Shortest Bridge — LeetCode 934 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Depth-First Search, Breadth-First Search, Array, Matrix
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- grid = [[0,1],[1,0]]
- Output
- 1
Python solution
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
def dfs(i, j):
q.append((i, j))
grid[i][j] = 2
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and grid[x][y] == 1:
dfs(x, y)
n = len(grid)
dirs = (-1, 0, 1, 0, -1)
q = deque()
i, j = next((i, j) for i in range(n) for j in range(n) if grid[i][j])
dfs(i, j)
ans = 0
while 1:
for _ in range(len(q)):
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n:
if grid[x][y] == 1:
return ans
if grid[x][y] == 0:
grid[x][y] = 2
q.append((x, y))
ans += 1Complexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 934. Shortest Bridge is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0130 | Surrounded Regions | Medium |
| 0200 | Number of Islands | Medium |
| 0417 | Pacific Atlantic Water Flow | Medium |
| 0463 | Island Perimeter | Easy |
| 0529 | Minesweeper | Medium |
| 0695 | Max Area of Island | Medium |
Frequently asked questions
- How hard is LeetCode 934. Shortest Bridge?
LeetCode 934. Shortest Bridge is rated Medium on LeetCode.
- What is the time complexity of LeetCode 934. Shortest Bridge?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 934. Shortest Bridge?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 934. Shortest Bridge cover?
LeetCode 934. Shortest Bridge is tagged Depth-First Search, Breadth-First Search, Array and Matrix on LeetCode.