#695
Max Area of Island
medium· Graphsruns: 0Given a binary matrix grid where 1 represents land and 0 represents water, return the maximum area of an island in grid. The area of an island is the number of cells with value 1 in the island. An island is a 4-directionally connected group of 1s. If there is no island, return 0.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 754
class Solution:
def maxAreaOfIsland(self, grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
def dfs(r: int, c: int) -> int:
if (
r < 0
or r >= rows
or c < 0
or c >= cols
or grid[r][c] == 0
):
return 0
grid[r][c] = 0
return (
1
+ dfs(r + 1, c)
+ dfs(r - 1, c)
+ dfs(r, c + 1)
+ dfs(r, c - 1)
)
best = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
best = max(best, dfs(r, c))
return best
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.