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→1 or 1→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
Path Vulnerability: Single Point of FailureStartCritical××EndBOTTLENECKVulnerable Grid: Single critical pathStartEndREDUNDANT PATHSRobust Grid: Multiple independent paths🎯 Key InsightA grid is vulnerable if there exists a single cell (bottleneck)whose removal disconnects all paths from start to endMax Flow ≤ 1 ⟺ Min Cut ≤ 1 ⟺ Vulnerable to Single Flip
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

n
2n
Linear Growth
Space Complexity
O(mn)

Space for flow network representation

n
2n
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
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
31.2K Views
Medium Frequency
~25 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen