Graph Theory37 sections · 1633 units
Open in Course

LeetCode 695 Max Area of Island - Implementation

LeetCode 695

Here's the solution in pseudocode:

function maxAreaOfIsland(grid):
    maxArea := 0
    rows := number of rows in grid
    cols := number of columns in grid

    for r from 0 to rows - 1:
        for c from 0 to cols - 1:
            if grid[r][c] = 1:
                area := dfs(grid, r, c)
                maxArea := max(maxArea, area)

    return maxArea

function dfs(grid, r, c):
    if r < 0 or r >= rows or c < 0 or c >= cols:
        return 0
    if grid[r][c] = 0:
        return 0

    grid[r][c] := 0
    area := 1
    area := area + dfs(grid, r + 1, c)
    area := area + dfs(grid, r - 1, c)
    area := area + dfs(grid, r, c + 1)
    area := area + dfs(grid, r, c - 1)
    return area

You modify the grid in place to mark visited cells. This avoids needing a separate visited set. Each DFS call returns the size of the connected component it explores. The main loop tracks the maximum across all islands.

Time: O(m×n)O(m \times n) since each cell is visited once. Space: O(m×n)O(m \times n) for the recursion stack in the worst case (a single snake-shaped island).