-
Notifications
You must be signed in to change notification settings - Fork 0
/
max-area-of-island.py
69 lines (51 loc) · 2.39 KB
/
max-area-of-island.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
"""
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
"""
from sys import maxsize
from typing import List
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
# Would probably be useful to have a "visited" hashmap to ensure we don't duplicate values or look at the same island twice
# Will use also a "seen_this_time" hashmap to not double count squares on the same island
global_seen = {}
height = len(grid)
width = len(grid[0])
def getLandLength(start_row_idx, start_col_idx):
if start_row_idx < 0 or start_row_idx >= height or start_col_idx < 0 or start_col_idx >= width:
return 0
this_tuple = (start_row_idx, start_col_idx)
if this_tuple in global_seen:
return 0
if grid[start_row_idx][start_col_idx] == 0:
return 0
global_seen[this_tuple] = True
up = getLandLength(start_row_idx + 1, start_col_idx)
down = getLandLength(start_row_idx - 1, start_col_idx)
left = getLandLength(start_row_idx, start_col_idx + 1)
right = getLandLength(start_row_idx, start_col_idx - 1)
return 1 + up + down + left + right
max_island_size = 0
for row_idx in range(height):
for col_idx in range(width):
if grid[row_idx][col_idx] == 0:
continue
if (row_idx, col_idx) in global_seen:
continue
max_island_size = max(
max_island_size, getLandLength(row_idx, col_idx))
return max_island_size
x = Solution()
this_grid = [
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
[0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
]
# this_grid = [[0,0,0,0,0,0,0,0]]
print(x.maxAreaOfIsland(this_grid))