-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisland_size.py
More file actions
98 lines (82 loc) · 2.93 KB
/
Copy pathisland_size.py
File metadata and controls
98 lines (82 loc) · 2.93 KB
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
94
95
96
97
98
"""
Two solutions presented for the Exercise 695 of Leetcode.
The aim is to find the maximum area of an island given a binary grid.
The idea is to find the maximum size of the connected component (4 directions)
in the grid.
Method: Depth-first Search
"""
def maxAreaOfIsland(grid):
"""
Function returning the greatest area of all the connected components
in the grid (if any).
:param grid: List[List[int]]
:return: int
"""
seen = set()
def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
and (r, c) not in seen and grid[r][c]):
return 0
seen.add((r, c))
return (1 + area(r + 1, c) + area(r - 1, c) +
area(r, c - 1) + area(r, c + 1))
return max(area(r, c)
for r in range(len(grid))
for c in range(len(grid[0])))
def maxAreaOfIsland2(grid):
"""
Function returning the greatest area of all the connected components
in the grid (if any).
:param grid: List[List[int]]
:return: int
"""
# Size of the matrix grid
m, n = len(grid), len(grid[0])
# Def custom class
class Node:
def __init__(self, i, j):
self.value = grid[i][j]
self.visited = False
# Corners of the grid
# TODO: Fix recursion issue here
if i == 0 and j == 0:
self.neighbors = [Node(0, 1), Node(1, 0)]
elif i == m - 1 and j == n - 1:
self.neighbors = [Node(m - 1, n - 2), Node(m - 2, n - 1)]
elif i == 0:
self.neighbors = [Node(0, j - 1), Node(0, j + 1),
Node(1, j + 1)]
elif j == 0:
self.neighbors = [Node(i - 1, 0), Node(i, 1),
Node(i + 1, 0)]
elif i == m - 1:
self.neighbors = [Node(m - 2, j), Node(m - 1, j + 1)]
elif j == n - 1:
self.neighbors = [Node(i, n - 2), Node(i - 1, n - 1),
Node(i + 1, n - 1)]
else:
self.neighbors = [Node(i - 1, j), Node(i, j - 1),
Node(i, j + 1), Node(i + 1, j + 1)]
connected_compo = []
def exploreNode(node):
tmp = []
if node.visited:
return tmp
node.visited = True
if node.value == 0:
return tmp
tmp.append(node)
for PosNeighbor in [n for n in node.neighbors if n.value == 1]:
tmp.extend(exploreNode(PosNeighbor))
return tmp
for i in range(0, m):
for j in range(0, n):
node = Node(i, j)
if node.visited:
continue
connected_compo.append(exploreNode(node))
print(connected_compo)
return max([len(c) for c in connected_compo])
if __name__ == "__main__":
grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
print(maxAreaOfIsland(grid))