There is a 1-based binary matrix where 0 represents land and 1
represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.
Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array
cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).
You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in thefour cardinal directions (left, right, up, and down).
Return thelast day where it is possible to walk from the top to the
bottom by only walking on land cells.

Input: row =2, col =2, cells =[[1,1],[2,1],[1,2],[2,2]]Output: 2Explanation: The above image depicts how the matrix changes each day starting from day 0.The last day where it is possible to cross from top to bottom is on day 2.

Input: row =2, col =2, cells =[[1,1],[1,2],[2,1],[2,2]]Output: 1Explanation: The above image depicts how the matrix changes each day starting from day 0.The last day where it is possible to cross from top to bottom is on day 1.

Input: row =3, col =3, cells =[[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]Output: 3Explanation: The above image depicts how the matrix changes each day starting from day 0.The last day where it is possible to cross from top to bottom is on day 3.
We want to find the last day we can cross from the top to the bottom row before water blocks all possible paths. Since the process is monotonic (once a cell is flooded, it stays flooded), we can use binary search to efficiently find the answer. For each day, we check if a path exists using BFS.
classSolution {
public:int latestDayToCross(int row, int col, vector<vector<int>>& cells) {
int l =0, r = cells.size() -1, ans =0;
vector<vector<int>> dirs = {{0,1},{1,0},{0,-1},{-1,0}};
auto canCross = [&](int day) {
vector<vector<int>> grid(row, vector<int>(col, 0));
for (int i =0; i <= day; ++i) grid[cells[i][0]-1][cells[i][1]-1] =1;
queue<pair<int,int>> q;
vector<vector<bool>> vis(row, vector<bool>(col, false));
for (int j =0; j < col; ++j) if (!grid[0][j]) { q.push({0,j}); vis[0][j] = true; }
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
if (x == row-1) return true;
for (auto& d : dirs) {
int nx = x + d[0], ny = y + d[1];
if (nx >=0&& nx < row && ny >=0&& ny < col &&!grid[nx][ny] &&!vis[nx][ny]) {
vis[nx][ny] = true;
q.push({nx, ny});
}
}
}
return false;
};
while (l <= r) {
int m = l + (r-l)/2;
if (canCross(m)) { ans = m; l = m+1; }
else r = m-1;
}
return ans+1;
}
};
classSolution {
publicintlatestDayToCross(int row, int col, int[][] cells) {
int l = 0, r = cells.length-1, ans = 0;
int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
java.util.function.IntPredicate canCross = day -> {
int[][] grid =newint[row][col];
for (int i = 0; i <= day; i++) grid[cells[i][0]-1][cells[i][1]-1]= 1;
boolean[][] vis =newboolean[row][col];
java.util.Queue<int[]> q =new java.util.LinkedList<>();
for (int j = 0; j < col; j++) if (grid[0][j]== 0) { q.add(newint[]{0,j}); vis[0][j]=true; }
while (!q.isEmpty()) {
int[] cur = q.poll();
if (cur[0]== row-1) returntrue;
for (int[] d : dirs) {
int nx = cur[0]+d[0], ny = cur[1]+d[1];
if (nx >= 0 && nx < row && ny >= 0 && ny < col && grid[nx][ny]== 0 &&!vis[nx][ny]) {
vis[nx][ny]=true;
q.add(newint[]{nx, ny});
}
}
}
returnfalse;
};
while (l <= r) {
int m = l + (r-l)/2;
if (canCross.test(m)) { ans = m; l = m+1; }
else r = m-1;
}
return ans+1;
}
}
classSolution {
funlatestDayToCross(row: Int, col: Int, cells: Array<IntArray>): Int {
val dirs = arrayOf(intArrayOf(0,1), intArrayOf(1,0), intArrayOf(0,-1), intArrayOf(-1,0))
funcanCross(day: Int): Boolean {
val grid = Array(row) { IntArray(col) }
for (i in0..day) grid[cells[i][0]-1][cells[i][1]-1] = 1val vis = Array(row) { BooleanArray(col) }
val q = ArrayDeque<Pair<Int,Int>>()
for (j in0 until col) if (grid[0][j] ==0) { q.add(0 to j); vis[0][j] = true }
while (q.isNotEmpty()) {
val(x, y) = q.removeFirst()
if (x == row-1) returntruefor (d in dirs) {
val nx = x + d[0]; val ny = y + d[1]
if (nx in0 until row && ny in0 until col && grid[nx][ny] ==0&& !vis[nx][ny]) {
vis[nx][ny] = true q.add(nx to ny)
}
}
}
returnfalse }
var l = 0; var r = cells.size-1; var ans = 0while (l <= r) {
val m = l + (r-l)/2if (canCross(m)) { ans = m; l = m+1 } else r = m-1 }
return ans+1 }
}
classSolution:
deflatestDayToCross(self, row: int, col: int, cells: list[list[int]]) -> int:
from collections import deque
dirs = [(0,1),(1,0),(0,-1),(-1,0)]
defcan_cross(day: int) -> bool:
grid = [[0]*col for _ in range(row)]
for i in range(day+1):
r, c = cells[i][0]-1, cells[i][1]-1 grid[r][c] =1 vis = [[False]*col for _ in range(row)]
q = deque()
for j in range(col):
if grid[0][j] ==0:
q.append((0, j))
vis[0][j] =Truewhile q:
x, y = q.popleft()
if x == row-1:
returnTruefor dx, dy in dirs:
nx, ny = x+dx, y+dy
if0<= nx < row and0<= ny < col and grid[nx][ny] ==0andnot vis[nx][ny]:
vis[nx][ny] =True q.append((nx, ny))
returnFalse l, r, ans =0, len(cells)-1, 0while l <= r:
m = l + (r-l)//2if can_cross(m):
ans = m
l = m+1else:
r = m-1return ans+1
impl Solution {
pubfnlatest_day_to_cross(row: i32, col: i32, cells: Vec<Vec<i32>>) -> i32 {
let row = row asusize;
let col = col asusize;
let dirs = [(0,1),(1,0),(0,-1),(-1,0)];
let can_cross =|day: usize| -> bool {
letmut grid =vec![vec![0; col]; row];
for i in0..=day { grid[(cells[i][0]-1) asusize][(cells[i][1]-1) asusize] =1; }
letmut vis =vec![vec![false; col]; row];
letmut q = std::collections::VecDeque::new();
for j in0..col { if grid[0][j] ==0 { q.push_back((0,j)); vis[0][j] =true; } }
whilelet Some((x, y)) = q.pop_front() {
if x == row-1 { returntrue; }
for (dx, dy) in dirs.iter() {
let nx = x asi32+ dx;
let ny = y asi32+ dy;
if nx >=0&& nx < row asi32&& ny >=0&& ny < col asi32 {
let (nx, ny) = (nx asusize, ny asusize);
if grid[nx][ny] ==0&&!vis[nx][ny] {
vis[nx][ny] =true;
q.push_back((nx, ny));
}
}
}
}
false };
let (mut l, mut r, mut ans) = (0, cells.len()-1, 0);
while l <= r {
let m = l + (r-l)/2;
if can_cross(m) { ans = m; l = m+1; } else { r = m-1; }
}
(ans+1) asi32 }
}