Imagine you're standing at the edge of a vast island that's slowly being consumed by rising floodwaters. Every day, more land disappears beneath the waves, and you need to find the last possible day you can still walk from the northern shore to the southern shore.
You start with a row ร col grid representing your island, where initially every cell is land (0). Each day, exactly one cell becomes flooded with water (1) according to a predetermined schedule given in the cells array.
Your goal is to determine the last day when you can still find a path from any cell in the top row to any cell in the bottom row, walking only on land cells and moving in the four cardinal directions (up, down, left, right).
Input: Three parameters - row (number of rows), col (number of columns), and cells (a 1-indexed array where cells[i] = [r, c] means cell at row r, column c floods on day i).
Output: Return the last day number when crossing from top to bottom is still possible.
Input & Output
example_1.py โ Basic Island
$Input:row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]
โบOutput:2
๐ก Note:Day 0: All land, can cross. Day 1: (1,1) floods, can still cross via (1,2)โ(2,2). Day 2: (2,1) floods, can still cross via (1,2)โ(2,2). Day 3: (1,2) floods, cannot reach bottom row. Answer: Day 2 is the last day we can cross.
example_2.py โ 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) floods, can cross via (1,2)โ(2,2). Day 2: (1,2) floods, cannot reach any bottom cell. Answer: Day 1 is the last day.
example_3.py โ Larger 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:After 3 days of flooding, there's still a path from top row to bottom row. After day 4, when (2,2) floods, the path gets blocked. So day 3 is the last valid day.
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
Understanding the Visualization
1
Day 0: Virgin Island
All cells are land, multiple paths exist from north to south
2
Early Days: Partial Flooding
Some cells flood but alternative paths remain available
3
Critical Day: Last Crossing
Final day when at least one path still connects top to bottom
4
Cutoff Day: No Path
Flooding has severed all connections between north and south shores
Key Takeaway
๐ฏ Key Insight: Since flooding is irreversible, the ability to cross follows a monotonic pattern - if day X blocks crossing, all days after X also block it. This makes binary search the perfect optimization technique!
The optimal approach uses binary search combined with BFS to efficiently find the last day when crossing is possible. Since flooding is irreversible (monotonic property), we can binary search the day range and validate each candidate with BFS pathfinding. This achieves O(n log n ร m) time complexity, significantly better than the brute force O(nยฒ ร m) approach.
Common Approaches
Approach
Time
Space
Notes
โ
Binary Search + BFS (Optimal)
O(n log n ร m)
O(m)
Use binary search to find the last valid day, with BFS to verify each candidate
Brute Force (Day-by-Day Simulation)
O(nยฒ ร m)
O(m)
Simulate flooding day by day and check path existence using BFS/DFS
Binary Search + BFS (Optimal) โ Algorithm Steps
Set binary search bounds: left = 0, right = len(cells)
While left < right:
- Calculate mid = (left + right + 1) // 2
- Simulate flooding up to day mid
- Use BFS to check if path exists from top to bottom
- If path exists: left = mid (try later days)
- If no path: right = mid - 1 (try earlier days)
Return left as the last valid day
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Initial Range
Start with full range [0, n] where n is total days
2
Test Middle
Test day (0+n)/2, simulate flooding and check path with BFS
3
Narrow Range
If path exists, search later days; if not, search earlier days
4
Converge
Continue until finding exact last day when crossing is possible
Code -
solution.c โ C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct {
int r, c;
} Point;
typedef struct {
Point* data;
int front, rear, size;
} Queue;
Queue* createQueue(int capacity) {
Queue* q = malloc(sizeof(Queue));
q->data = malloc(capacity * sizeof(Point));
q->front = q->rear = 0;
q->size = capacity;
return q;
}
void enqueue(Queue* q, Point p) {
q->data[q->rear] = p;
q->rear = (q->rear + 1) % q->size;
}
Point dequeue(Queue* q) {
Point p = q->data[q->front];
q->front = (q->front + 1) % q->size;
return p;
}
bool isEmpty(Queue* q) {
return q->front == q->rear;
}
bool canCrossOnDay(int day, int row, int col, int** cells) {
// Create grid and simulate flooding up to given day
int** grid = malloc(row * sizeof(int*));
for (int i = 0; i < row; i++) {
grid[i] = calloc(col, sizeof(int));
}
for (int i = 0; i < day; i++) {
int r = cells[i][0] - 1, c = cells[i][1] - 1;
grid[r][c] = 1;
}
// BFS to check if path exists
Queue* queue = createQueue(row * col);
bool** visited = malloc(row * sizeof(bool*));
for (int i = 0; i < row; i++) {
visited[i] = calloc(col, sizeof(bool));
}
// Start from all land cells in top row
for (int c = 0; c < col; c++) {
if (grid[0][c] == 0) {
Point p = {0, c};
enqueue(queue, p);
visited[0][c] = true;
}
}
int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool result = false;
while (!isEmpty(queue)) {
Point curr = dequeue(queue);
int r = curr.r, c = curr.c;
// Reached bottom row?
if (r == row - 1) {
result = true;
break;
}
// Explore neighbors
for (int i = 0; i < 4; i++) {
int nr = r + directions[i][0], nc = c + directions[i][1];
if (nr >= 0 && nr < row && nc >= 0 && nc < col &&
grid[nr][nc] == 0 && !visited[nr][nc]) {
Point p = {nr, nc};
enqueue(queue, p);
visited[nr][nc] = true;
}
}
}
// Cleanup
for (int i = 0; i < row; i++) {
free(grid[i]);
free(visited[i]);
}
free(grid);
free(visited);
free(queue->data);
free(queue);
return result;
}
int latestDayToCross(int row, int col, int** cells, int cellsSize) {
// Binary search for the last day we can cross
int left = 0, right = cellsSize;
while (left < right) {
int mid = (left + right + 1) / 2;
if (canCrossOnDay(mid, row, col, cells)) {
left = mid; // Can cross on day mid, try later days
} else {
right = mid - 1; // Cannot cross, try earlier days
}
}
return left;
}
int main() {
int row, col, n;
scanf("%d %d", &row, &col);
scanf("%d", &n);
int** cells = malloc(n * sizeof(int*));
for (int i = 0; i < n; i++) {
cells[i] = malloc(2 * sizeof(int));
scanf("%d %d", &cells[i][0], &cells[i][1]);
}
printf("%d\n", latestDayToCross(row, col, cells, n));
for (int i = 0; i < n; i++) free(cells[i]);
free(cells);
return 0;
}
Time & Space Complexity
Time Complexity
โฑ๏ธ
O(n log n ร m)
Binary search O(log n) iterations, each requiring O(n + m) for flooding simulation and BFS
n
2n
โก Linearithmic
Space Complexity
O(m)
Grid storage and BFS queue, where m = row ร col
n
2n
โ Linear Space
28.5K Views
MediumFrequency
~25 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐กExplanation
AI Ready
๐ก SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom โข Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
๐ก
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
๐ง
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
๐ก
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
๐ฌ
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
๐ง
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
๐ก
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
๐งช
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
๐
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
โก
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
๐ป
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
๐ฌ
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
๐ก
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.