-
Notifications
You must be signed in to change notification settings - Fork 2
/
200.py
93 lines (78 loc) · 2.8 KB
/
200.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# [ LeetCode ] 200. Number of Islands
def solution(grid: list[list[int]]) -> int:
def validate_island(grid: list[list[int]], row: int, column: int):
if (
(row >= 0 and row <len(grid))
and
(column >= 0 and column < len(grid[0]))
):
if grid[row][column] == "1":
grid[row][column] = "0"
validate_island(grid=grid, row=row-1, column=column)
validate_island(grid=grid, row=row+1, column=column)
validate_island(grid=grid, row=row, column=column-1)
validate_island(grid=grid, row=row, column=column+1)
else:
return None
else:
return None
answer: int = 0
for row in range(len(grid)):
for column in range(len(grid[0])):
if grid[row][column] == "1":
answer += 1
validate_island(grid=grid, row=row, column=column)
return answer
def another_solution(grid: list[list[int]]) -> int:
M, N = len(grid), len(grid[0])
visited: list[list[bool]] = [[False] * N for _ in range(M)]
def dbs(row: int, column: int) -> None:
if (
(row >= 0 and row < M)
and
(column >= 0 and column < N)
and
grid[row][column] == "1"
and
not visited[row][column]
):
visited[row][column] = True
dbs(row=row-1, column=column)
dbs(row=row+1, column=column)
dbs(row=row, column=column-1)
dbs(row=row, column=column+1)
answer: int = 0
for row in range(M):
for column in range(N):
if grid[row][column] == "1" and not visited[row][column]:
answer += 1
dbs(row=row, column=column)
return answer
if __name__ == "__main__":
cases: list[dict[str, dict[str, list[list[int]]] | int]] = [
{
"input": {
"grid": [
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]
]
},
"output": 1
},
{
"input": {
"grid": [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
]
},
"output": 3
}
]
for case in cases:
assert case["output"] == another_solution(grid=case["input"]["grid"])
assert case["output"] == solution(grid=case["input"]["grid"])