#1970
Hard Algorithms Last day where you can still cross
Array Binary Search Depth-First Search Breadth-First Search Union-Find Matrix
68.6% acceptance
Feb 25, 2026
2374
48
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 the four cardinal directions (left, right, up, and down).
Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn latest_day_to_cross(row: i32, col: i32, cells: Vec<Vec<i32>>) -> i32 {
let row = row as usize;
let col = col as usize;
let _n = row * col;
// Binary search on the day
// For a given day d, flood cells[0..d], check if top-to-bottom path exists on land
let mut lo = 1i32;
let mut hi = cells.len() as i32;
while lo < hi {
let mid = lo + (hi - lo + 1) / 2;
if Self::can_cross(row, col, &cells, mid as usize) {
lo = mid;
} else {
hi = mid - 1;
}
}
lo
}
fn can_cross(row: usize, col: usize, cells: &[Vec<i32>], day: usize) -> bool {
let mut grid = vec![vec![0u8; col]; row];
for i in 0..day {
let r = (cells[i][0] - 1) as usize;
let c = (cells[i][1] - 1) as usize;
grid[r][c] = 1; // water
}
// BFS from top row
use std::collections::VecDeque;
let mut queue = VecDeque::new();
let mut visited = vec![vec![false; col]; row];
for c in 0..col {
if grid[0][c] == 0 {
queue.push_back((0, c));
visited[0][c] = true;
}
}
let dirs = [(0i32, 1i32), (0, -1), (1, 0), (-1, 0)];
while let Some((r, c)) = queue.pop_front() {
if r == row - 1 {
return true;
}
for &(dr, dc) in &dirs {
let nr = r as i32 + dr;
let nc = c as i32 + dc;
if nr >= 0 && nr < row as i32 && nc >= 0 && nc < col as i32 {
let nr = nr as usize;
let nc = nc as usize;
if !visited[nr][nc] && grid[nr][nc] == 0 {
visited[nr][nc] = true;
queue.push_back((nr, nc));
}
}
}
}
false
}
}