File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments