Tensorum
LeetCode 778 · Minimum Spanning Tree

Swim in Rising Water

LeetCode 778 · Hard · solution, intuition & step-by-step walkthrough

Min-heap of max-height-so-far along the path.

HardArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-Find
28 msruntime · beats 50%
20 MBmemory · beats 30%
1approach
9accepted runs · last 30 Apr 2026

This is how I solved Swim in Rising Water (LeetCode 778), a hard problem from the Minimum Spanning Tree pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

You can cross a cell once the water level reaches its height, so a path's time is the highest cell on it. Expand cells in order of that bottleneck with a min-heap (Prim/Dijkstra style); when the bottom-right is popped, its value is the answer.

Approach

  1. 1

    Heap starts with (grid[0][0], 0, 0).

  2. 2

    Pop the lowest; target → return its time.

  3. 3

    Skip visited cells; push neighbours with max(time, height).

How I solved it

Dijkstra / Prim on bottleneckPythonO(n² log n) time
#TC - N^2logN SC - N^2
class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        #prims algo
        #minimum edge weights to reach the destination
        min_heap = [(grid[0][0],0,0)] #time,row,col
        visited = set()
        n = len(grid)
        di = [0,+1,0,-1]
        dj = [+1,0,-1,0]
        while min_heap: #Maximum it can visit N^2 cells
            time,row,col = heapq.heappop(min_heap) #logN
            if row==n-1 and col==n-1:
                return time
            if (row,col) in visited:
                continue
            visited.add((row,col))
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<n and 0<=ncol<n and (nrow,ncol) not in visited:
                    heapq.heappush(min_heap,(max(time,grid[nrow][ncol]),nrow,ncol))
        return -1
Loading the step-through…

Swim in Rising Water — FAQ

What is the intuition behind Swim in Rising Water?

You can cross a cell once the water level reaches its height, so a path's time is the highest cell on it. Expand cells in order of that bottleneck with a min-heap (Prim/Dijkstra style); when the bottom-right is popped, its value is the answer.

How do you solve Swim in Rising Water (LeetCode 778)?

1. Heap starts with (grid[0][0], 0, 0). 2. Pop the lowest; target → return its time. 3. Skip visited cells; push neighbours with max(time, height).

What is the time and space complexity of Swim in Rising Water?

Time: O(n² log n). Space: O(n²). (Accepted approach: Dijkstra / Prim on bottleneck.)

What are common mistakes in Swim in Rising Water?

Binary search on time + BFS also works.