CodingNodes / Advanced Graphs / Swim In Rising Water System design Space play · ←→ step · R restart

Problem

An n × n grid holds the elevation of every cell, and the elevations are all different: they are the numbers 0 to n² − 1 in some order. It starts raining, and at time t the water level is t.

You start in the top-left cell and want to reach the bottom-right cell. In one move you step to a cell directly above, below, left or right, and you may stand on a cell only when its elevation is at most the current water level (you can swim any distance instantly). Return the smallest time at which you can reach the bottom-right cell.

Constraints

  • n = grid.length = grid[i].length, 1 ≤ n ≤ 50
  • 0 ≤ grid[i][j] < n²
  • Every value in grid is different

Examples: pick one to animate

Solutions

TimeO(n² log n) SpaceO(n²)

Time: Each of the n² cells is pushed once and popped once, and a heap of up to n² entries costs about log n² = 2 log n per operation.

Space: The seen table and the heap together hold at most one entry per cell.

Treat the time you can stand on a cell as its cost: the highest elevation on the path so far. Keep a min-heap of (time, row, col), starting with the top-left cell. Always pop the cell with the smallest time. When you step to a neighbour, you reach it at max(time, its elevation). The first time the bottom-right cell is popped, no other route can reach it earlier, so that time is the answer. Marking a cell as seen when it is pushed is safe because pops come out in non-decreasing time. The code uses its own array heap (parent of index i is (i − 1) / 2), so the array and tree you see are the real thing.