Skip to content

Commit 6e12f1f

Browse files
Create swim_in_rising_water.py
1 parent a71618f commit 6e12f1f

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

matrix/swim_in_rising_water.py

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

0 commit comments

Comments
 (0)