Skip to content

Commit 6033e4b

Browse files
committed
- Number of Islands DaleStudy#258
1 parent 1c32a78 commit 6033e4b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

number-of-islands/ayosecu.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(N), N = The number of items = len(grid) * len(grid[0])
6+
- Space Complexity: O(N)
7+
- In worst case (all "1"s), The depth of dfs is N => O(N)
8+
"""
9+
def numIslands(self, grid: List[List[str]]) -> int:
10+
m, n = len(grid), len(grid[0])
11+
12+
def dfs(i, j):
13+
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != "1":
14+
return
15+
16+
grid[i][j] = "#" # Visited
17+
for dx, dy in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
18+
dfs(i + dx, j + dy)
19+
20+
count = 0
21+
for i in range(m):
22+
for j in range(n):
23+
if grid[i][j] == "1":
24+
count += 1
25+
dfs(i, j)
26+
27+
return count
28+
29+
tc = [
30+
([
31+
["1","1","1","1","0"],
32+
["1","1","0","1","0"],
33+
["1","1","0","0","0"],
34+
["0","0","0","0","0"]
35+
], 1),
36+
([
37+
["1","1","0","0","0"],
38+
["1","1","0","0","0"],
39+
["0","0","1","0","0"],
40+
["0","0","0","1","1"]
41+
], 3)
42+
]
43+
44+
sol = Solution()
45+
for i, (grid, e) in enumerate(tc, 1):
46+
r = sol.numIslands(grid)
47+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)