-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path693.py
77 lines (75 loc) · 3.05 KB
/
693.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
__________________________________________________________________________________________________
sample 124 ms submission
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
row_n = len(grid)
col_n = len(grid[0])
res = 0
for i in range(row_n):
for j in range(col_n):
if grid[i][j]:
area = 0
stack = [(i, j)]
grid[i][j] = 0
while stack:
cur_i, cur_j = stack.pop()
area += 1
if cur_i - 1 >= 0 and grid[cur_i - 1][cur_j]:
stack.append((cur_i - 1, cur_j))
grid[cur_i - 1][cur_j] = 0
if cur_i + 1 < row_n and grid[cur_i + 1][cur_j]:
stack.append((cur_i + 1, cur_j))
grid[cur_i + 1][cur_j] = 0
if cur_j - 1 >= 0 and grid[cur_i][cur_j - 1]:
stack.append((cur_i, cur_j - 1))
grid[cur_i][cur_j - 1] = 0
if cur_j + 1 < col_n and grid[cur_i][cur_j + 1]:
stack.append((cur_i, cur_j + 1))
grid[cur_i][cur_j + 1] = 0
res = max(res, area)
return res
__________________________________________________________________________________________________
sample 14840 kb submission
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_size = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
grid[i][j] = 0
size = self.explore_island(grid, i, j, size=1)
if size > max_size:
max_size = size
return max_size
def explore_island(self, grid, i, j, size):
neighbours = []
#print("In cell {}, {}, size is {}".format(str(i), str(j), str(size)))
#search up
if i>0:
if grid[i-1][j] == 1:
neighbours.append((i-1, j))
grid[i-1][j] = 0
size += 1
#search right
if j<len(grid[0])-1:
if grid[i][j+1] == 1:
neighbours.append((i, j+1))
grid[i][j+1] = 0
size += 1
#search down
if i<len(grid)-1:
if grid[i+1][j] == 1:
neighbours.append((i+1, j))
grid[i+1][j] = 0
size += 1
#search left
if j>0:
if grid[i][j-1] == 1:
neighbours.append((i, j-1))
grid[i][j-1] = 0
size += 1
#print("After neighbour search size {}".format(str(size)))
for n in neighbours:
size = self.explore_island(grid, n[0], n[1], size)
return size
__________________________________________________________________________________________________