Skip to content

Commit 1dd5e6d

Browse files
committed
Add problem 778 - Swim In Rising Water
1 parent 82074b4 commit 1dd5e6d

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import heapq
2+
from typing import List
3+
4+
5+
class SwimInRisingWater:
6+
@staticmethod
7+
def swimInWater(grid: List[List[int]]) -> int:
8+
# Dimensions of the grid
9+
n = len(grid)
10+
# Min heap to store the cells based on the lowest value
11+
min_heap = [(grid[0][0], 0, 0)]
12+
# Array to mark the visited cells
13+
visited = [[False] * n for _ in range(n)]
14+
visited[0][0] = True
15+
# Directions
16+
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
17+
# Loop until heap is empty
18+
while min_heap:
19+
time, i, j = heapq.heappop(min_heap)
20+
# Check if we have reached the last cell
21+
if i == n - 1 and j == n - 1:
22+
return time
23+
# Move in all four directions
24+
for direction in directions:
25+
x, y = i + direction[0], j + direction[1]
26+
# Check for out of bounds
27+
if x < 0 or x >= n or y < 0 or y >= n or visited[x][y]:
28+
continue
29+
visited[x][y] = True
30+
heapq.heappush(min_heap, (max(grid[x][y], time), x, y))
31+
return -1
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import unittest
2+
3+
from problems.graph.swim_in_rising_water import SwimInRisingWater
4+
5+
6+
class TestSwimInRisingWater(unittest.TestCase):
7+
def test_swim_in_water(self):
8+
swim_in_rising_water = SwimInRisingWater()
9+
10+
# Test case 1
11+
grid1 = [[0, 2], [1, 3]]
12+
expected1 = 3
13+
self.assertEqual(swim_in_rising_water.swimInWater(grid1), expected1)
14+
15+
# Test case 2
16+
grid2 = [
17+
[0, 1, 2, 3, 4],
18+
[24, 23, 22, 21, 5],
19+
[12, 13, 14, 15, 16],
20+
[11, 17, 18, 19, 20],
21+
[10, 9, 8, 7, 6]
22+
]
23+
expected2 = 16
24+
self.assertEqual(swim_in_rising_water.swimInWater(grid2), expected2)
25+
26+
# Edge case: single cell
27+
grid3 = [[0]]
28+
expected3 = 0
29+
self.assertEqual(swim_in_rising_water.swimInWater(grid3), expected3)
30+
31+
# Edge case: larger grid
32+
grid4 = [
33+
[0, 1, 2],
34+
[3, 4, 5],
35+
[6, 7, 8]
36+
]
37+
expected4 = 8
38+
self.assertEqual(swim_in_rising_water.swimInWater(grid4), expected4)
39+
40+
41+
if __name__ == "__main__":
42+
unittest.main()

0 commit comments

Comments
 (0)