You are given a 0-indexedm x nbinary 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 trueif it is possible to make the matrix disconnect orfalseotherwise.
Note that flipping a cell changes its value from 0 to 1 or from 1 to
0.

Input: grid =[[1,1,1],[1,0,0],[1,1,1]]Output: trueExplanation: We can change the cell shown in the diagram above. There is no path from(0,0) to (2,2)in the resulting grid.

Input: grid =[[1,1,1],[1,0,1],[1,1,1]]Output: falseExplanation: It is not possible to change at most one cell such that there is not path from(0,0) to (2,2).
If there is only one unique path from (0,0) to (m-1,n-1), then flipping any cell (except the endpoints) on that path will disconnect the matrix. If there are two or more disjoint paths, then no single flip can disconnect the matrix. So, check if there is more than one path.
classSolution {
publicbooleanisPossibleToCutPath(int[][] grid) {
int m = grid.length, n = grid[0].length;
if (!dfs(grid, 0, 0, m, n)) returntrue;
return!dfs(grid, 0, 0, m, n);
}
privatebooleandfs(int[][] grid, int x, int y, int m, int n) {
if (x < 0 || y < 0 || x >= m || y >= n || grid[x][y]== 0) returnfalse;
if (x == m-1 && y == n-1) returntrue;
grid[x][y]= 0;
boolean res = dfs(grid, x+1, y, m, n) || dfs(grid, x, y+1, m, n);
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funisPossibleToCutPath(grid: Array<IntArray>): Boolean {
val m = grid.size
val n = grid[0].size
fundfs(x: Int, y: Int): Boolean {
if (x !in0 until m || y !in0 until n || grid[x][y] ==0) returnfalseif (x == m-1&& y == n-1) returntrue grid[x][y] = 0return dfs(x+1, y) || dfs(x, y+1)
}
dfs(0, 0)
return !dfs(0, 0)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defisPossibleToCutPath(self, grid: list[list[int]]) -> bool:
m, n = len(grid), len(grid[0])
defdfs(x: int, y: int) -> bool:
if x <0or y <0or x >= m or y >= n or grid[x][y] ==0:
returnFalseif x == m-1and y == n-1:
returnTrue grid[x][y] =0return dfs(x+1, y) or dfs(x, y+1)
dfs(0, 0)
returnnot dfs(0, 0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnis_possible_to_cut_path(mut grid: Vec<Vec<i32>>) -> bool {
let m = grid.len();
let n = grid[0].len();
fndfs(grid: &mut Vec<Vec<i32>>, x: usize, y: usize, m: usize, n: usize) -> bool {
if x >= m || y >= n || grid[x][y] ==0 { returnfalse; }
if x == m-1&& y == n-1 { returntrue; }
grid[x][y] =0;
dfs(grid, x+1, y, m, n) || dfs(grid, x, y+1, m, n)
}
dfs(&mut grid, 0, 0, m, n);
!dfs(&mut grid, 0, 0, m, n)
}
}