2556. Disconnect Path in a Binary Matrix by at Most One Flip
Description
You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1) that has the value 1. The matrix is disconnected if there is no path from (0, 0) to (m - 1, n - 1).
You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0) and (m - 1, n - 1).
Return true if it is possible to make the matrix disconnect or false otherwise.
Note that flipping a cell changes its value from 0 to 1 or from 1 to 0.
Example 1:
Input: grid = [[1,1,1],[1,0,0],[1,1,1]] Output: true Explanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid.
Example 2:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: false Explanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2).
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 105grid[i][j]is either0or1.grid[0][0] == grid[m - 1][n - 1] == 1
Solutions
Solution 1: Two DFS Traversals
Thinking
Moves are only right or down. We may flip at most one non-endpoint cell to disconnect \((0,0)\) from the exit. Trying every flip is cubic.
Two internally vertex-disjoint paths cannot be cut by a single flip. DFS once, zeroing visited cells (then restore the two ends), and DFS again: a second success means a disjoint path remains, so one flip is not enough.
First, we perform a DFS traversal to determine whether there is a path from \((0, 0)\) to \((m - 1, n - 1)\), and we denote the result as \(a\). During the DFS process, we set the value of the visited cells to \(0\) to prevent revisiting.
Next, we set the values of \((0, 0)\) and \((m - 1, n - 1)\) to \(1\), and perform another DFS traversal to determine whether there is a path from \((0, 0)\) to \((m - 1, n - 1)\), and we denote the result as \(b\). During the DFS process, we set the value of the visited cells to \(0\) to avoid revisiting.
Finally, if both \(a\) and \(b\) are true, we return false, otherwise, we return true.
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Where \(m\) and \(n\) are the number of rows and columns of the matrix, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |

