Skip to content

Commit b05ec5a

Browse files
committed
solve : number of islands
1 parent ecb74c9 commit b05ec5a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

number-of-islands/samthekorean.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# TC : O(n) where n is the number of elements in the two-dimensional list.
2+
# SC : O(n) where n is the depth of the stack of recursive calls.
3+
class Solution:
4+
def numIslands(self, grid: List[List[str]]) -> int:
5+
def dfs(r, c):
6+
# Mark the current cell as visited by setting it to "0"
7+
grid[r][c] = "0"
8+
# Explore all four possible directions (right, down, left, up)
9+
for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
10+
nr, nc = r + dr, c + dc
11+
# Check if the new position is within bounds and is land ("1")
12+
if (
13+
0 <= nr < len(grid)
14+
and 0 <= nc < len(grid[0])
15+
and grid[nr][nc] == "1"
16+
):
17+
dfs(nr, nc)
18+
19+
island_count = 0
20+
# Traverse each cell in the grid
21+
for r in range(len(grid)):
22+
for c in range(len(grid[0])):
23+
if grid[r][c] == "1": # Found an island
24+
island_count += 1 # Increment the island count
25+
dfs(r, c) # Sink the entire island
26+
return island_count # Return the total number of islands

0 commit comments

Comments
 (0)