-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.py
77 lines (62 loc) · 4.3 KB
/
solution.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
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
# 25%
'''
if not(grid) or not(grid[0]): return 0
rowN , colN = len(grid), len(grid[0])
def helper(x, y, grid):
if x<0 or y<0 or x>=rowN or y>=colN or grid[x][y]=="0":
return 0
dist = 1
grid[x][y] = "0"
dist+=helper(x+1, y, grid) # int +string -> time-consuming
dist+=helper(x, y+1, grid)
dist+=helper(x-1, y, grid)
dist+=helper(x, y-1, grid)
return dist
counter = 0
for i in range(rowN):
for j in range(colN):
result = helper(i, j, grid)
if result: counter+=1
return counter
# 35%
if not(grid) or not(grid[0]): return 0
rowN , colN = len(grid), len(grid[0])
def helper(x, y, grid):
if x<0 or y<0 or x>=rowN or y>=colN or grid[x][y]=="0":
return
grid[x][y] = "0"
helper(x+1, y, grid) # int +string -> time-consuming
helper(x, y+1, grid)
helper(x-1, y, grid)
helper(x, y-1, grid)
counter = 0
for i in range(rowN):
for j in range(colN):
if grid[i][j]=="1": counter+=1
helper(i, j, grid)
return counter
'''
# 45%
if not(grid) or not(grid[0]): return 0
rowN , colN = len(grid), len(grid[0])
def helper(x, y, grid):
if x<0 or y<0 or x>=rowN or y>=colN or grid[x][y]=="0":
return
grid[x][y] = "0"
helper(x+1, y, grid) # int +string -> time-consuming
helper(x, y+1, grid)
helper(x-1, y, grid)
helper(x, y-1, grid)
counter = 0
for i in range(rowN):
for j in range(colN):
if grid[i][j]=="1": #onlu check islands
counter+=1
helper(i, j, grid)
return counter