↻one more pass.
Advanced graphs · Hard

Swim In Rising Water: the idea to remember.

Find the minimum water level allowing a four direction path between opposite corners of an elevation grid.

Solve on LeetCode ↗

The core insight

Expand the lowest available frontier cell and track the highest elevation encountered.

Why it works

A cell becomes reachable when water covers the least demanding frontier; the first complete path minimizes its maximum elevation.

The mistake to avoid

The path cost is its maximum cell height, not the sum of heights. Include the starting cell elevation.

Time: O(n² log n)Space: O(n²)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Expand the lowest available frontier cell and track the highest elevation encountered.
private int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };

public int swimInWater(int[][] grid) {
    int len = grid.length;

    if (len == 1) {
        return 0;
    }

    var seen = new boolean[len][len];
    seen[0][0] = true;

    var minHeap = new PriorityQueue<Integer[]>((a, b) -> a[0] - b[0]);
    minHeap.add(new Integer[] { grid[0][0], 0, 0 });

    int result = 0;

    while (!minHeap.isEmpty()) {
        var curr = minHeap.poll();

        result = Math.max(result, curr[0]);

        if (curr[1] == len - 1 && curr[2] == len - 1) {
            break;
        }

        for (int i = 0; i < 4; i++) {
            int x = curr[1] + dirs[i][0];
            int y = curr[2] + dirs[i][1];

            if (x < 0 || x >= len || y < 0 || y >= len || seen[x][y]) {
                continue;
            }

            minHeap.add(new Integer[] { grid[x][y], x, y });
            seen[x][y] = true;
        }
    }

    return result;
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.