Disconnect Path in a Binary Matrix by at Most One Flip - Problem
You're given an m × n binary matrix representing a grid where you can only move through cells containing 1. Your goal is to determine if you can disconnect the path from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1) by flipping at most one cell.
Movement Rules:
- From cell
(row, col), you can move to(row + 1, col)or(row, col + 1) - You can only move to cells with value
1
Flipping Rules:
- You can flip at most one cell (changing
0→1or1→0) - You cannot flip the start
(0, 0)or end(m-1, n-1)cells
Return true if you can make the matrix disconnected, false otherwise.
Input & Output
example_1.py — Basic disconnectable grid
$
Input:
grid = [[1,1,1],[1,0,0],[1,1,1]]
›
Output:
true
💡 Note:
We can flip grid[1][0] from 1 to 0, making it impossible to reach from (0,0) to (2,2). The path through (1,0) is the only way to connect the regions.
example_2.py — Multiple paths available
$
Input:
grid = [[1,1,1],[1,1,0],[1,1,1]]
›
Output:
false
💡 Note:
There are multiple independent paths from (0,0) to (2,2). Even if we flip one cell, alternative routes still exist, so we cannot disconnect the grid with just one flip.
example_3.py — Already disconnected
$
Input:
grid = [[1,0,0],[1,1,0],[0,1,1]]
›
Output:
true
💡 Note:
The grid is already disconnected - there's no path from (0,0) to (2,2). Since we can achieve disconnection without any flips, the answer is true.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Critical Paths
Find all possible routes from start to end
2
Analyze Bottlenecks
Look for single points of failure in the network
3
Apply Graph Theory
Use max-flow to determine minimum cut capacity
4
Make Decision
If min-cut ≤ 1, the path is vulnerable to single flip
Key Takeaway
🎯 Key Insight: Use max-flow min-cut theorem: if maximum flow ≤ 1, then minimum cut ≤ 1, meaning one cell flip can disconnect the path
Time & Space Complexity
Time Complexity
O(mn(m+n))
Max flow in grid graph using Edmonds-Karp algorithm
✓ Linear Growth
Space Complexity
O(mn)
Space for flow network representation
⚡ Linearithmic Space
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 50
- grid[i][j] is either 0 or 1
- grid[0][0] == grid[m - 1][n - 1] == 1
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code