|
| 1 | +import heapq |
| 2 | + |
| 3 | + |
| 4 | +def swim_in_rising_water(grid: list[list[int]]) -> int: |
| 5 | + """ |
| 6 | + Return the minimum time to reach the bottom right square of the grid |
| 7 | + from the top left, where time t allows swimming to cells with |
| 8 | + elevation <= t. |
| 9 | +
|
| 10 | + This is a variant of Dijkstra's shortest path algorithm using a |
| 11 | + priority queue (min-heap) to find the minimum elevation (time) path |
| 12 | + in a grid graph. |
| 13 | +
|
| 14 | + Reference: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm |
| 15 | +
|
| 16 | + :param grid: n x n integer matrix where grid[i][j] is the elevation |
| 17 | + at (i, j) |
| 18 | + :return: Minimum time to reach (n-1, n-1) from (0, 0) |
| 19 | +
|
| 20 | + Examples: |
| 21 | + >>> swim_in_rising_water([[0, 2], [1, 3]]) |
| 22 | + 3 |
| 23 | + >>> grid = [ |
| 24 | + ... [0, 1, 2, 3, 4], |
| 25 | + ... [24, 23, 22, 21, 5], |
| 26 | + ... [12, 13, 14, 15, 16], |
| 27 | + ... [11, 17, 18, 19, 20], |
| 28 | + ... [10, 9, 8, 7, 6] |
| 29 | + ... ] |
| 30 | + >>> swim_in_rising_water(grid) |
| 31 | + 16 |
| 32 | + >>> swim_in_rising_water([[0]]) # n=1 edge case |
| 33 | + 0 |
| 34 | + >>> swim_in_rising_water([[5, 3], [4, 2]]) # Another small grid |
| 35 | + 5 |
| 36 | + """ |
| 37 | + if not grid or not grid[0]: |
| 38 | + raise ValueError("Grid must be a non-empty n x n matrix") |
| 39 | + |
| 40 | + n = len(grid) |
| 41 | + if n != len(grid[0]): |
| 42 | + raise ValueError("Grid must be square (n x n)") |
| 43 | + |
| 44 | + # Directions: right, down, left, up |
| 45 | + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] |
| 46 | + |
| 47 | + # Min-heap: (max_elevation_so_far, row, col) |
| 48 | + min_heap: list[tuple[int, int, int]] = [(grid[0][0], 0, 0)] |
| 49 | + visited = [[False] * n for _ in range(n)] |
| 50 | + visited[0][0] = True |
| 51 | + |
| 52 | + while min_heap: |
| 53 | + max_elev, r, c = heapq.heappop(min_heap) |
| 54 | + |
| 55 | + # Reached bottom-right |
| 56 | + if r == n - 1 and c == n - 1: |
| 57 | + return max_elev |
| 58 | + |
| 59 | + for dr, dc in directions: |
| 60 | + nr, nc = r + dr, c + dc |
| 61 | + if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc]: |
| 62 | + visited[nr][nc] = True |
| 63 | + # The time is the max elevation encountered on this path |
| 64 | + new_elev = max(max_elev, grid[nr][nc]) |
| 65 | + heapq.heappush(min_heap, (new_elev, nr, nc)) |
| 66 | + |
| 67 | + # Should always reach if grid is valid, but for completeness |
| 68 | + raise ValueError("No path found to bottom-right (grid constraints violated)") |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + import doctest |
| 73 | + |
| 74 | + doctest.testmod() |
0 commit comments