Algo-Sim › Grid Graphs
Swim in Rising Water
Hard · Grid Graphs · step through it in Java, Python and C++ on your own input
The fastest route minimises its highest cell. Dijkstra with a min-heap where a path’s cost is its maximum, not its sum.
Problem
An n × n grid holds elevations (a permutation of 0 … n² − 1). At time t the water everywhere is t deep, and you can swim between 4-directional neighbours when both elevations are at most t; swimming takes no time. Starting at the top-left, return the least time at which you can reach the bottom-right.
Constraints
- 1 ≤ n ≤ 50
- 0 ≤ grid[i][j] < n²
- Every value appears exactly once
Edge cases to test
- 1 × 1 grid
- The highest cell is the start or the end
- An increasing spiral
Follow-up questions
- What else works?
- Binary search on the time with a flood fill, or union-find adding cells in height order until the corners connect.
- What is the cost?
- O(n² log n) with a heap over n² cells.
Solution
Java
public int swimInWater(int[][] grid) {
int n = grid.length;
boolean[][] seen = new boolean[n][n];
// Entries are { time, row, col }; break time ties by row, then column.
PriorityQueue<int[]> pq = new PriorityQueue<>(
Comparator.<int[]>comparingInt(a -> a[0])
.thenComparingInt(a -> a[1]).thenComparingInt(a -> a[2]));
pq.offer(new int[] { grid[0][0], 0, 0 });
seen[0][0] = true;
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (true) {
int[] cur = pq.poll();
int t = cur[0], r = cur[1], c = cur[2];
if (r == n - 1 && c == n - 1) return t;
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nc < 0 || nr >= n || nc >= n || seen[nr][nc]) continue;
seen[nr][nc] = true;
pq.offer(new int[] { Math.max(t, grid[nr][nc]), nr, nc });
}
}
}Python
import heapq
def swim_in_water(grid):
n = len(grid)
seen = {(0, 0)}
pq = [(grid[0][0], 0, 0)] # (time, row, col)
while True:
t, r, c = heapq.heappop(pq)
if r == n - 1 and c == n - 1:
return t
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if not (0 <= nr < n and 0 <= nc < n) or (nr, nc) in seen:
continue
seen.add((nr, nc))
heapq.heappush(pq, (max(t, grid[nr][nc]), nr, nc))C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int swimInWater(vector<vector<int>> &grid) {
int n = int(grid.size());
vector<vector<bool>> seen = vector<vector<bool>>(n, vector<bool>(n));
// Entries are { time, row, col }: the earliest time that cell can be reached.
priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
pq.push(vector<int>{grid[0][0], 0, 0});
seen[0][0] = true;
vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (true) {
vector<int> cur = pq.top();
pq.pop();
int t = cur[0], r = cur[1], c = cur[2];
if (r == n - 1 && c == n - 1)
return t;
for (vector<int> &d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nc < 0 || nr >= n || nc >= n || seen[nr][nc])
continue;
seen[nr][nc] = true;
pq.push(vector<int>{std::max(t, grid[nr][nc]), nr, nc});
}
}
}
};
More Grid Graphs problems
- Flood Fill (Easy)
- Number of Islands (BFS) (Medium)
- Number of Islands (DFS) (Medium)
- Max Area of Island (Medium)
- Rotting Oranges (Medium)
- 01 Matrix (Medium)
- Walls and Gates (Medium)
- Shortest Path in Binary Matrix (Medium)
- Shortest Bridge (Medium)
- Shortest Path in a Grid with Obstacles Elimination (Hard)
- Surrounded Regions (Medium)
- Pacific Atlantic Water Flow (Medium)
- Path With Minimum Effort (Medium)
- Minimum Cost to Make at Least One Valid Path in a Grid (Hard)