Disconnect Path in a Binary Matrix by at Most One Flip Problem
Description
LeetCode Problem 2556.
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 <= 10^5grid[i][j]is either0or1.grid[0][0] == grid[m - 1][n - 1] == 1
Solution
Approach: Two DFS Passes
Flipping one cell (other than the two ends) disconnects the grid exactly when all paths from the top-left to the bottom-right share some cell. That is the case unless there are two paths that touch only at the two ends.
Run a DFS (moving only down or right) from (0, 0) that marks every visited cell as 0, and note whether it reaches (m - 1, n - 1). This finds one path and removes the cells it explored. Restore the two end cells, then run the DFS again. If both runs find a path, two cell-disjoint paths exist and one flip cannot disconnect the grid, so return false; otherwise return true.
Complexity: O(mn) time and O(m + n) extra space for the recursion.
class Solution:
def isPossibleToCutPath(self, grid: List[List[int]]) -> bool:
def dfs(i, j):
if i >= m or j >= n or grid[i][j] == 0:
return False
grid[i][j] = 0
if i == m - 1 and j == n - 1:
return True
return dfs(i + 1, j) or dfs(i, j + 1)
m, n = len(grid), len(grid[0])
a = dfs(0, 0)
grid[0][0] = grid[-1][-1] = 1
b = dfs(0, 0)
return not (a and b)