695. Max Area of Island
doing some more basic questions before the next tech round.
1class Solution:
2 def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
3 if not grid or not grid[0]:
4 return 0
5
6 result = 0
7 m, n = len(grid), len(grid[0])
8 directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
9
10 for i in range(m):
11 for j in range(n):
12 if grid[i][j] == 1:
13 grid[i][j] = 0
14 island_area = 0
15 dq = deque([(i, j)])
16 while dq:
17 ci, cj = dq.popleft()
18 island_area += 1
19
20 for di, dj in directions:
21 ni, nj = ci + di, cj + dj
22 if 0 <= ni < m and 0 <= nj < n and grid[ni][nj] == 1:
23 grid[ni][nj] = 0
24 dq.append((ni, nj))
25
26 result = max(result, island_area)
27
28 return result
#Matrix #Breadth-First-Search #Python