Skip to content

Commit 551746a

Browse files
committed
add solution: number-of-islands
1 parent e2941b1 commit 551746a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

number-of-islands/dusunax.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'''
2+
# 200. Number of Islands
3+
4+
use DFS to find the number of islands (to find the all the possible cases)
5+
6+
## Time and Space Complexity
7+
8+
```
9+
TC: O(m * n)
10+
SC: O(m * n)
11+
```
12+
13+
### TC is O(m * n):
14+
- dfs function is called for each cell in the grid for checking is the land ("1") = O(m * n)
15+
16+
### SC is O(m * n):
17+
- using a recursive function, the call stack can go as deep as the number of cells in the grid in the worst case. = O(m * n)
18+
'''
19+
class Solution:
20+
def numIslands(self, grid: List[List[str]]) -> int:
21+
def dfs(x, y):
22+
if x < 0 or y < 0 or y >= len(grid) or x >= len(grid[0]) or grid[y][x] == "0" :
23+
return
24+
25+
grid[y][x] = "0"
26+
dfs(x, y + 1)
27+
dfs(x - 1, y)
28+
dfs(x, y - 1)
29+
dfs(x + 1, y)
30+
31+
island_count = 0
32+
for y in range(len(grid)):
33+
for x in range(len(grid[0])):
34+
if grid[y][x] == "1":
35+
dfs(x, y)
36+
island_count += 1
37+
38+
return island_count

0 commit comments

Comments
 (0)