150NeetCode 150

82.Max Area of Island

MediumGraphs · 3/19

Problem

You are given an m x n binary matrix grid, where 1 is land and 0 is water. An island is a group of 1s connected 4-directionally (up, down, left, right). The area of an island is the number of cells in it.

Return the maximum area of any island in grid. If there is no island, return 0.

Examples

Input:  grid = [
  [0,0,1,0,0,0,0,1,0,0,0,0,0],
  [0,0,0,0,0,0,0,1,1,1,0,0,0],
  [0,1,1,0,1,0,0,0,0,0,0,0,0],
  [0,1,0,0,1,1,0,0,1,0,1,0,0],
  [0,1,0,0,1,1,0,0,1,1,1,0,0],
  [0,0,0,0,0,0,0,0,0,0,1,0,0],
  [0,0,0,0,0,0,0,1,1,1,0,0,0],
  [0,0,0,0,0,0,0,1,1,0,0,0,0]
]
Output: 6
Explanation: The island in columns 8–10 of rows 3–5 has 6 cells. Diagonal cells do not connect, so it is not bigger.
Input:  grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Explanation: There is no land.
Input:  grid = [
  [1,1,0],
  [1,0,0],
  [0,1,1]
]
Output: 3
Explanation: Top-left island has area 3, bottom-right island has area 2.

Constraints

  • m == grid.length, n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1

💡 Key Insight

This is Number of Islands with one extra number per island: instead of just counting components, measure each one. A flood fill (DFS or BFS) started from an unvisited land cell visits exactly the cells of that island, so returning 1 + area(neighbours) gives its size. Mark cells as you visit them so every cell contributes to exactly one island, giving O(m·n) total.

Brute Force

TimeO((m·n)²)SpaceO(m·n)

Intuition

For every land cell, run a fresh BFS with its own visited array and count how many cells it reaches. That count is the area of the island containing this cell, so the maximum over all cells is the answer. Every cell of an island recomputes the same area, which is wasted work.

Algorithm

  1. For every cell (r, c) with grid[r][c] == 1:
    • BFS from (r, c) using a new visited array; count reached cells as area.
    • best = max(best, area).
  2. Return best.

Visualization

grid
1 1 0
1 0 0
0 1 1

(0,0): BFS reaches (0,0),(0,1),(1,0) → area 3   best = 3
(0,1): BFS reaches the same 3 cells  → area 3   (repeated work)
(1,0): area 3                                    (repeated work)
(2,1): BFS reaches (2,1),(2,2)       → area 2
(2,2): area 2
answer = 3

Code

java
import java.util.ArrayDeque;
import java.util.Deque;

class Solution {
    private static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public int maxAreaOfIsland(int[][] grid) {
        int best = 0;
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                if (grid[r][c] == 1) {
                    best = Math.max(best, islandSize(grid, r, c));
                }
            }
        }
        return best;
    }

    // Fresh BFS from (r, c), counting every reachable land cell
    private int islandSize(int[][] grid, int r, int c) {
        int rows = grid.length, cols = grid[0].length;
        boolean[][] visited = new boolean[rows][cols];
        Deque<int[]> queue = new ArrayDeque<>();
        queue.offer(new int[]{r, c});
        visited[r][c] = true;
        int area = 0;

        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            area++;
            for (int[] d : DIRS) {
                int nr = cell[0] + d[0], nc = cell[1] + d[1];
                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols
                        && !visited[nr][nc] && grid[nr][nc] == 1) {
                    visited[nr][nc] = true;
                    queue.offer(new int[]{nr, nc});
                }
            }
        }
        return area;
    }
}

Complexity

  • Time: O((m·n)²) — up to m·n land cells, each running a BFS (and allocating a visited array) of size up to m·n.
  • Space: O(m·n) — visited and the queue for one BFS.

Complexity Comparison

Approach Time Space
Brute Force O((m·n)²) O(m·n)
Union-Find with Sizes O(m·n·α(m·n)) O(m·n)
DFS O(m·n) O(m·n)

Common Pitfalls

  • Returning -1 or throwing when there is no land — the expected answer is 0.
  • Marking a cell visited after the recursive calls; neighbours then recurse back into it and the area is counted multiple times (or recursion never ends).
  • Counting diagonal cells as part of the same island.
  • In Union-Find, updating best with the size of a non-root node — sizes are only valid at roots.
  • Forgetting that DFS mutates grid; copy it first if the caller needs the original.