-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path200.py
65 lines (54 loc) · 1.67 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
from typing import List
# Name: Number of Islands
# Link: https://leetcode.com/problems/number-of-islands/
# Method: Traverse islands, mark as null
# Time: O(n*m)
# Space: O(n*m)
# Difficulty: Medium
DIRS = [[0, 1], [0, -1], [-1, 0], [1, 0]]
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
n = len(grid)
m = len(grid[0])
def explore_isle(i, j):
grid[i][j] = "2"
for oi, oj in DIRS:
i2 = i + oi
j2 = j + oj
if not (i2 < 0 or j2 < 0 or i2 >= n or j2 >= m) and grid[i2][j2] == "1":
explore_isle(i2, j2)
isles = 0
for i in range(n):
for j in range(m):
if grid[i][j] == "1":
explore_isle(i, j)
isles += 1
return isles
def numIslands_faster(self, grid: List[List[str]]) -> int:
n = len(grid)
m = len(grid[0])
def exp_isle(i, j):
grid[i][j] = "2"
for oi, oj in DIRS:
i2 = i + oi
j2 = j + oj
if not (i2 < 0 or j2 < 0 or i2 >= n or j2 >= m) and grid[i2][j2] == "1":
exp_isle(i2, j2)
isles = 0
for i in range(n):
for j in range(m):
if grid[i][j] == "1":
exp_isle(i, j)
isles += 1
return isles
if __name__ == "__main__":
a = [
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "1"],
["1", "1", "0", "0", "0"],
["1", "1", "1", "1", "1"],
]
sol = Solution()
print(sol.numIslands(a))