-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMax Area of Island.py
More file actions
38 lines (27 loc) · 893 Bytes
/
Max Area of Island.py
File metadata and controls
38 lines (27 loc) · 893 Bytes
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
from typing import List
class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
LAND = 1
WATER = 0
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
return max(self.island_area(i, j, grid) for i in range(n) for j in range(m))
@classmethod
def island_area(cls, row: int, col: int, grid: List[List[int]]) -> int:
if grid[row][col] != cls.LAND:
return 0
n, m = len(grid), len(grid[0])
grid[row][col] = cls.WATER
area = 1
if row > 0:
area += cls.island_area(row - 1, col, grid)
if row < n - 1:
area += cls.island_area(row + 1, col, grid)
if col > 0:
area += cls.island_area(row, col - 1, grid)
if col < m - 1:
area += cls.island_area(row, col + 1, grid)
return area