695. Max Area of Island (Medium) - TengnanYao/daily_leetcode GitHub Wiki
class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
seen = set()
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
result = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
if (i, j) not in seen:
cur = 0
q = collections.deque([(i, j)])
seen.add((i, j))
while q:
x, y = q.popleft()
cur += 1
for a, b in directions:
a += x
b += y
if 0 <= a < m and 0 <= b < n and (a, b) not in seen and grid[a][b] == 1:
q.append((a, b))
seen.add((a, b))
result = max(cur, result)
return result