#2556
Disconnect Path in a Binary Matrix by at Most One Flip
MediumArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchMatrixGraph TraversalBreadth-First SearchDepth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the idea of finding two non-intersecting paths from (0, 0) to (m - 1, n - 1). If such paths exist, flipping one cell won't disconnect the paths. This approach is efficient and avoids unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Perform a BFS or DFS to find the first path from (0, 0) to (m - 1, n - 1).
- 2Step 2: Mark all cells in the found path as visited.
- 3Step 3: Perform another BFS or DFS from (0, 0) to find a second path that does not intersect with the first path.
- 4Step 4: If a second path is found, return false. If not, return true.
solution.py31 lines
1# Full working Python code
2from collections import deque
3
4def canDisconnect(grid):
5 m, n = len(grid), len(grid[0])
6
7 def bfs(start, visited):
8 queue = deque([start])
9 path = []
10 while queue:
11 x, y = queue.popleft()
12 path.append((x, y))
13 if (x, y) == (m - 1, n - 1):
14 return path
15 for dx, dy in [(1, 0), (0, 1)]:
16 nx, ny = x + dx, y + dy
17 if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 1 and (nx, ny) not in visited:
18 visited.add((nx, ny))
19 queue.append((nx, ny))
20 return []
21
22 visited = set()
23 path1 = bfs((0, 0), visited)
24 if not path1:
25 return True
26
27 for x, y in path1:
28 visited.add((x, y))
29
30 path2 = bfs((0, 0), visited)
31 return len(path2) == 0ℹ
Complexity note: The time complexity is O(n) because we only traverse the grid a limited number of times, making it linear in terms of the number of cells.
- 1Finding two non-intersecting paths is crucial to determine if a disconnection is possible.
- 2BFS/DFS can efficiently explore paths in a grid-like structure.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.