-
Notifications
You must be signed in to change notification settings - Fork 7
/
solution.py
28 lines (26 loc) · 910 Bytes
/
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
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid: return 0
self.m = len(grid)
self.n = len(grid[0])
result = 0
self.seen = set()
max_area = 0
for m in range(self.m):
for n in range(self.n):
if self.maxArea(m, n, grid):
result += 1
return result
def maxArea(self, i, j, grid):
if (i, j) in self.seen or grid[i][j] == '0':
return 0
self.seen.add((i, j))
up = 0 if i == 0 else self.maxArea(i-1, j, grid)
down = 0 if i == self.m - 1 else self.maxArea(i+1, j, grid)
left = 0 if j == 0 else self.maxArea(i, j-1, grid)
right = 0 if j == self.n - 1 else self.maxArea(i, j+1, grid)
return 1 + up + down + left + right