</>

778. Swim in Rising Water

Hard NeetCode 150
Advanced Graphs Time O(n^2 log n) Space O(n^2)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Advanced Graphs
Time
O(n^2 log n)
Space
O(n^2)

Standard Solution (C++)

SummaryOn a grid where each cell has an elevation and water level rises over time, find the earliest time you can travel from the top-left to the bottom-right, only entering cells whose elevation is at or below the current water level.

Approach

Dijkstra-style min-heap on the minimax path. The cost of a path is the maximum elevation along it; we want the path that minimizes this maximum.

  • Use a min-heap ordered by the largest elevation seen so far on the path.
  • Always expand the lowest-bottleneck cell; the first time we pop the destination, that bottleneck value is the answer.
class Solution {
public:
    int swimInWater(vector<vector<int>>& grid) {
        int n = grid.size();
        vector<vector<bool>> visited(n, vector<bool>(n, false));
        priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq;
        pq.push({grid[0][0], 0, 0}); // (time, row, col)
        int dirs[5] = {-1, 0, 1, 0, -1};
        while (!pq.empty()) {
            auto [t, r, c] = pq.top(); pq.pop();
            if (r == n - 1 && c == n - 1) return t;
            if (visited[r][c]) continue;
            visited[r][c] = true;
            for (int d = 0; d < 4; ++d) {
                int nr = r + dirs[d], nc = c + dirs[d+1];
                if (nr < 0 || nc < 0 || nr >= n || nc >= n) continue;
                if (visited[nr][nc]) continue;
                pq.push({max(t, grid[nr][nc]), nr, nc});
            }
        }
        return -1;
    }
};
Time O(n^2 log n) Space O(n^2)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern