Last Day Where You Can Still Cross - Problem

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.

Input & Output

Example 1 — Basic Grid
$ Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]
Output: 2
💡 Note: Day 0: All land, path exists. Day 1: (1,1) flooded, path exists via (1,2)→(2,2). Day 2: (2,1) flooded, path exists via (1,2)→(2,2). Day 3: (1,2) flooded, no path from top to bottom.
Example 2 — Narrow Path
$ Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]
Output: 1
💡 Note: Day 0: All land. Day 1: (1,1) flooded, path via (1,2)→(2,2). Day 2: (1,2) flooded, no path from top row to bottom row.
Example 3 — Large Grid
$ Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,1],[3,2]]
Output: 3
💡 Note: Larger grid allows more flooding before path is completely blocked between top and bottom rows.

Constraints

  • 2 ≤ row, col ≤ 2 × 104
  • 4 ≤ row × col ≤ 2 × 104
  • cells.length == row × col
  • 1 ≤ ri ≤ row
  • 1 ≤ ci ≤ col
  • All the values of cells are unique.

Visualization

Tap to expand
Last Day Where You Can Still CrossDay 0000000000✓ Path existsDay 2000110000✓ Path via rightDay 3001110000✗ No path!Valid pathAnswer: Day 2 (last day with valid path)
Understanding the Visualization
1
Initial State
All cells are land (0), path exists from any top to any bottom
2
Daily Flooding
Each day one cell becomes water (1) according to cells array
3
Path Checking
Find last day when path still exists from top row to bottom row
Key Takeaway
🎯 Key Insight: Use binary search on days + BFS to efficiently find the last valid crossing day
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
18.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen