Swim in Rising Water

Dijkstra where edge weight is the destination cell's height — the path cost is the max along the path.

Hard
Time O(n^2 log n) Space O(n^2)
LeetCode
7 min read
dijkstra grid binary-search

Problem#

An n x n grid where grid[i][j] is the platform’s elevation. At time t, you can move into any cell whose elevation is at most t. Return the minimum time to travel from (0, 0) to (n-1, n-1).

Examples#

  • grid = [[0,2],[1,3]]3
  • grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]16

Constraints#

  • n == grid.length == grid[i].length, 1 <= n <= 50, 0 <= grid[i][j] < n^2.

Approach#

Treat the grid as a graph where the “cost” of a path is the maximum elevation along it. Use Dijkstra with a min-heap ordered by max-elevation-so-far; pop the smallest, expand to neighbors with max(curCost, neighborHeight).

Solution#

Swim in Rising Water
class Solution {
public:
int swimInWater(vector<vector<int>>& grid) {
int n = grid.size();
vector<vector<int>> dist(n, vector<int>(n, INT_MAX));
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
dist[0][0] = grid[0][0];
pq.push({grid[0][0], 0, 0});
int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
while (!pq.empty()) {
auto [d, r, c] = pq.top(); pq.pop();
if (r == n - 1 && c == n - 1) return d;
if (d > dist[r][c]) continue;
for (int k = 0; k < 4; ++k) {
int nr = r + dx[k], nc = c + dy[k];
if (nr < 0 || nr >= n || nc < 0 || nc >= n) continue;
int nd = max(d, grid[nr][nc]);
if (nd < dist[nr][nc]) {
dist[nr][nc] = nd;
pq.push({nd, nr, nc});
}
}
}
return -1;
}
};

Editorial#

The “max along path” cost is a valid Dijkstra metric because it’s monotonic when extended. Each cell’s optimal entry-time is the smallest max-height of any path reaching it. The heap is sized by n^2 and each cell relaxes at most O(1) times.

Complexity#

  • Time: O(n^2 log n).
  • Space: O(n^2).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.