Learning pathsPricingA
← DSA problem library

DSA-094 · FOCUSED PRACTICE

Maximum Area of Island

Core · Java 21 · Version 1 · editorial draft

Java reference and baseline verified on JDK 21: 3395 deterministic checks. Learner drafts are not executed.

Understand the problem

Return the largest number of cells in any orthogonally connected island of ones in a binary grid. Return zero when no land exists.

  • The outer array is nonnull and rectangular with nonnull rows, at most 100,000 rows and 100,000 cells. Size bounds are preconditions; null outer input throws NullPointerException and null/ragged rows throw IllegalArgumentException. Zero rows or zero columns are allowed.
  • Every cell is 0 or 1; reject any other value before traversal. Only up/right/down/left adjacency connects land. Diagonal contact alone does not join components.
  • Preserve all source cell values and row references; shared input row objects are allowed because coordinates, not row objects, identify vertices.

Examples

  1. Input: [[1,1,0],[0,1,0],[1,0,1]]
    Output: 3

    The top component has three cells; two isolated bottom cells do not add to its area.

  2. Input: [[1,0],[0,1]]
    Output: 1

    Diagonal ones are two separate one-cell islands.

Before you start

  • Component traversal and coordinate-indexed visited state
  • Distinguishing component area from component count (DSA-093)

Recognize the structure

The grid is an implicit graph with one vertex per land coordinate and at most four candidate neighbors. A global visited matrix gives each connected component one owner, avoiding a new full exploration from every land seed.

Your Java attempt

Java 21 · Draft only. Your code is not compiled, executed, or graded here. Run it locally against the examples and edge cases.

Saving stores text in this browser, visible to other people using this browser profile. It does not sync to your account. Loading is always explicit.

No unsaved text changes · 149/20,000 characters

Self-review

Use the checklist to test your explanation. Checks apply to this visit.

Try before revealing

Hint 1

An island is a connected component of one-valued coordinates.

Hint 2

Use one shared visited matrix across the entire outer scan.

Hint 3

Count each popped cell and update best only after that component exhausts.

Derive the solution

Reveal the baseline, optimized reasoning, and Java code

Recount the component from every land seed

For each one, create a fresh visited matrix, explore everything connected to that seed, and compare its count with best. In a three-cell island this repeats the same exploration three times. The baseline is iterative and correct but can take quadratic work; sharing visited ownership across seed scans removes this repetition.

Improve the baseline

Validate before using cell codes

Check all row shapes and all binary values. Use a separate visited matrix so inputs, including aliased source rows, remain read-only.

Claim on enqueue and count on pop

At an unvisited land seed, mark it and enqueue it. Each valid unclaimed land neighbor is marked before enqueueing, preventing duplicate owners when two frontier cells meet.

Compare only finished component areas

Increment area for each popped cell. Once the queue empties, that component is complete and best can be updated; the row-major scan then finds the next unclaimed component.

Why it is correct

Connectivity invariant

Every queued or processed cell is land connected to its component seed by claimed orthogonal land edges. No water or diagonal-only cell can enter.

Unique ownership and complete coverage

Marking before enqueue gives every land cell one owner. Any land reachable from a seed has a path whose next unclaimed neighbor is eventually expanded, so the finished traversal contains the whole component.

Maximum over the partition

The outer scan starts once per component. Each final area counts exactly its distinct cells; maximizing these values gives the largest island, with zero for an empty partition.

Complete Java reference and baseline

Save as Solution.java. Node definitions and imports are included where needed. The baseline is included for comparison; respect its input-size limits.

import java.util.*;
public final class Solution {
    private static final int[][] DIRECTIONS = {{-1,0},{0,1},{1,0},{0,-1}};
    private static int validate(int[][] grid) {
        Objects.requireNonNull(grid,"grid");
        int columns=grid.length==0?0:grid[0]==null?-1:grid[0].length;
        for(int[] row:grid) {
            if(row==null||row.length!=columns)throw new IllegalArgumentException("nonrectangular grid");
            for(int value:row) if(value!=0&&value!=1)throw new IllegalArgumentException("invalid cell");
        }
        return columns;
    }
    public static int maxArea(int[][] grid) {
        int columns=validate(grid),best=0;
        boolean[][] visited=new boolean[grid.length][columns];
        ArrayDeque<int[]> queue=new ArrayDeque<>();
        for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++) {
            if(grid[r][c]!=1||visited[r][c])continue;
            int area=0;visited[r][c]=true;queue.addLast(new int[]{r,c});
            while(!queue.isEmpty()) {
                int[] cell=queue.removeFirst();area++;
                for(int[] d:DIRECTIONS) {
                    int nr=cell[0]+d[0],nc=cell[1]+d[1];
                    if(nr<0||nr>=grid.length||nc<0||nc>=columns||grid[nr][nc]!=1||visited[nr][nc])continue;
                    visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});
                }
            }
            best=Math.max(best,area);
        }
        return best;
    }
    public static int baseline(int[][] grid) {
        int columns=validate(grid),best=0;
        for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++)if(grid[r][c]==1) {
            boolean[][] visited=new boolean[grid.length][columns];ArrayDeque<int[]> queue=new ArrayDeque<>();
            visited[r][c]=true;queue.addLast(new int[]{r,c});int area=0;
            while(!queue.isEmpty()) {
                int[] cell=queue.removeFirst();area++;
                for(int[] d:DIRECTIONS) {int nr=cell[0]+d[0],nc=cell[1]+d[1];if(nr>=0&&nr<grid.length&&nc>=0&&nc<columns&&grid[nr][nc]==1&&!visited[nr][nc]){visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});}}
            }
            best=Math.max(best,area);
        }
        return best;
    }
}

Read the meaningful blocks

Visited is not area

A queued coordinate is already claimed but is counted only when popped; temporary queue size is neither area nor depth.

Keep source values independent

Writing zero into the input would change the read-only API and can interact with shared row references.

Separate largest area from number of starts

Incrementing a component count solves Number of Islands; this API maximizes the number of cells within one start.

Complexity

Let R be row count, B total cells, and N=R+B, so validation/row allocation still count when rows have zero columns. Main time is O(N), with O(N) auxiliary visited/queue storage and one scalar output. Every land coordinate is enqueued once and has four neighbor checks.

The repeated-seed baseline costs O(N(B+1)) worst-case time, reducing to O(B²) for nonempty rectangles, and O(N) peak auxiliary storage. Empty-row validation remains O(R), not an unexplained constant.

Exact-state walkthroughs

Reveal normal and boundary traces

Component areas are compared after completion

Input: [[1,1,0],[0,1,0],[1,0,1]] · Maximum island area: 3

Step 1 of 15: Begin a scan with no claimed land.

A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

Island area — component ownership and finished maximum

Phase: initial.

Unchanged source grid

110
010
101

Coordinate queue — front at left; already claimed

Empty.

✓ = discovered land. Current component popped area: 0. Largest finished area: 0. Queued cells count toward area only when popped; the maximum updates after the component finishes. Water is 0 and land is 1; only orthogonal contact connects land.

The exact state table and static walkthrough below provide the same information without relying on color.

State after this step
VariableValue
source[[1,1,0],[0,1,0],[1,0,1]]
grid[[1,1,0],[0,1,0],[1,0,1]]
queue[]
visited[[false,false,false],[false,false,false],[false,false,false]]
area0
best0
seednull
completed[]
phase"initial"
currentnull
See the affected Java block
 1 import java.util.*;
 2 public final class Solution {
 3     private static final int[][] DIRECTIONS = {{-1,0},{0,1},{1,0},{0,-1}};
 4     private static int validate(int[][] grid) {
 5         Objects.requireNonNull(grid,"grid");
 6         int columns=grid.length==0?0:grid[0]==null?-1:grid[0].length;
 7         for(int[] row:grid) {
 8             if(row==null||row.length!=columns)throw new IllegalArgumentException("nonrectangular grid");
 9             for(int value:row) if(value!=0&&value!=1)throw new IllegalArgumentException("invalid cell");
10         }
11         return columns;
12     }
13     public static int maxArea(int[][] grid) {
14         int columns=validate(grid),best=0;
15         boolean[][] visited=new boolean[grid.length][columns];
16         ArrayDeque<int[]> queue=new ArrayDeque<>();
17         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++) {
18             if(grid[r][c]!=1||visited[r][c])continue;
19             int area=0;visited[r][c]=true;queue.addLast(new int[]{r,c});
20             while(!queue.isEmpty()) {
21                 int[] cell=queue.removeFirst();area++;
22                 for(int[] d:DIRECTIONS) {
23                     int nr=cell[0]+d[0],nc=cell[1]+d[1];
24                     if(nr<0||nr>=grid.length||nc<0||nc>=columns||grid[nr][nc]!=1||visited[nr][nc])continue;
25                     visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});
26                 }
27             }
28             best=Math.max(best,area);
29         }
30         return best;
31     }
32     public static int baseline(int[][] grid) {
33         int columns=validate(grid),best=0;
34         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++)if(grid[r][c]==1) {
35             boolean[][] visited=new boolean[grid.length][columns];ArrayDeque<int[]> queue=new ArrayDeque<>();
36             visited[r][c]=true;queue.addLast(new int[]{r,c});int area=0;
37             while(!queue.isEmpty()) {
38                 int[] cell=queue.removeFirst();area++;
39                 for(int[] d:DIRECTIONS) {int nr=cell[0]+d[0],nc=cell[1]+d[1];if(nr>=0&&nr<grid.length&&nc>=0&&nc<columns&&grid[nr][nc]==1&&!visited[nr][nc]){visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});}}
40             }
41             best=Math.max(best,area);
42         }
43         return best;
44     }
45 }
46 

Highlight locates the relevant statement or block; one trace step may summarize several assignments.

Read the full static trace
  1. Begin a scan with no claimed land.

    A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[false,false,false],[false,false,false],[false,false,false]]
    area
    0
    best
    0
    seed
    null
    completed
    []
    phase
    "initial"
    current
    null
  2. Start one previously unclaimed component.

    Global visited ownership prevents recounting this component from another seed.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    [[0,0]]
    visited
    [[true,false,false],[false,false,false],[false,false,false]]
    area
    0
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "seed"
    current
    [0,0]
  3. Count one popped land coordinate.

    Queued cells are already claimed but contribute to area when popped. Source values remain unchanged.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,false,false],[false,false,false],[false,false,false]]
    area
    1
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "visit"
    current
    [0,0]
  4. Claim one orthogonally connected land neighbor.

    Each land coordinate enters one component queue once. Diagonal contact does not connect islands.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    [[0,1]]
    visited
    [[true,true,false],[false,false,false],[false,false,false]]
    area
    1
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "claim"
    current
    [0,0]
    claimed
    [0,1]
  5. Count one popped land coordinate.

    Queued cells are already claimed but contribute to area when popped. Source values remain unchanged.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,true,false],[false,false,false],[false,false,false]]
    area
    2
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "visit"
    current
    [0,1]
  6. Claim one orthogonally connected land neighbor.

    Each land coordinate enters one component queue once. Diagonal contact does not connect islands.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    [[1,1]]
    visited
    [[true,true,false],[false,true,false],[false,false,false]]
    area
    2
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "claim"
    current
    [0,1]
    claimed
    [1,1]
  7. Count one popped land coordinate.

    Queued cells are already claimed but contribute to area when popped. Source values remain unchanged.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,true,false],[false,true,false],[false,false,false]]
    area
    3
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "visit"
    current
    [1,1]
  8. Finish the component before comparing its full area.

    An empty queue certifies complete component coverage. best is the largest finished component, not the number of islands.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,true,false],[false,true,false],[false,false,false]]
    area
    3
    best
    3
    seed
    [0,0]
    completed
    [{"seed":[0,0],"area":3}]
    phase
    "component"
    current
    null
  9. Start one previously unclaimed component.

    Global visited ownership prevents recounting this component from another seed.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    [[2,0]]
    visited
    [[true,true,false],[false,true,false],[true,false,false]]
    area
    0
    best
    3
    seed
    [2,0]
    completed
    [{"seed":[0,0],"area":3}]
    phase
    "seed"
    current
    [2,0]
  10. Count one popped land coordinate.

    Queued cells are already claimed but contribute to area when popped. Source values remain unchanged.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,true,false],[false,true,false],[true,false,false]]
    area
    1
    best
    3
    seed
    [2,0]
    completed
    [{"seed":[0,0],"area":3}]
    phase
    "visit"
    current
    [2,0]
  11. Finish the component before comparing its full area.

    An empty queue certifies complete component coverage. best is the largest finished component, not the number of islands.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,true,false],[false,true,false],[true,false,false]]
    area
    1
    best
    3
    seed
    [2,0]
    completed
    [{"seed":[0,0],"area":3},{"seed":[2,0],"area":1}]
    phase
    "component"
    current
    null
  12. Start one previously unclaimed component.

    Global visited ownership prevents recounting this component from another seed.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    [[2,2]]
    visited
    [[true,true,false],[false,true,false],[true,false,true]]
    area
    0
    best
    3
    seed
    [2,2]
    completed
    [{"seed":[0,0],"area":3},{"seed":[2,0],"area":1}]
    phase
    "seed"
    current
    [2,2]
  13. Count one popped land coordinate.

    Queued cells are already claimed but contribute to area when popped. Source values remain unchanged.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,true,false],[false,true,false],[true,false,true]]
    area
    1
    best
    3
    seed
    [2,2]
    completed
    [{"seed":[0,0],"area":3},{"seed":[2,0],"area":1}]
    phase
    "visit"
    current
    [2,2]
  14. Finish the component before comparing its full area.

    An empty queue certifies complete component coverage. best is the largest finished component, not the number of islands.

    source
    [[1,1,0],[0,1,0],[1,0,1]]
    grid
    [[1,1,0],[0,1,0],[1,0,1]]
    queue
    []
    visited
    [[true,true,false],[false,true,false],[true,false,true]]
    area
    1
    best
    3
    seed
    [2,2]
    completed
    [{"seed":[0,0],"area":3},{"seed":[2,0],"area":1},{"seed":[2,2],"area":1}]
    phase
    "component"
    current
    null
  15. Return the documented value, changed-grid view, fresh result, or cloned graph view.

    Coordinates and object identities follow the problem-specific contract. Discovery histories are teaching views, not additional Java workspace.

    result
    3

Diagonal land remains separate

Input: [[1,0],[0,1]] · Maximum island area: 1

Step 1 of 8: Begin a scan with no claimed land.

A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

Island area — component ownership and finished maximum

Phase: initial.

Unchanged source grid

10
01

Coordinate queue — front at left; already claimed

Empty.

✓ = discovered land. Current component popped area: 0. Largest finished area: 0. Queued cells count toward area only when popped; the maximum updates after the component finishes. Water is 0 and land is 1; only orthogonal contact connects land.

The exact state table and static walkthrough below provide the same information without relying on color.

State after this step
VariableValue
source[[1,0],[0,1]]
grid[[1,0],[0,1]]
queue[]
visited[[false,false],[false,false]]
area0
best0
seednull
completed[]
phase"initial"
currentnull
See the affected Java block
 1 import java.util.*;
 2 public final class Solution {
 3     private static final int[][] DIRECTIONS = {{-1,0},{0,1},{1,0},{0,-1}};
 4     private static int validate(int[][] grid) {
 5         Objects.requireNonNull(grid,"grid");
 6         int columns=grid.length==0?0:grid[0]==null?-1:grid[0].length;
 7         for(int[] row:grid) {
 8             if(row==null||row.length!=columns)throw new IllegalArgumentException("nonrectangular grid");
 9             for(int value:row) if(value!=0&&value!=1)throw new IllegalArgumentException("invalid cell");
10         }
11         return columns;
12     }
13     public static int maxArea(int[][] grid) {
14         int columns=validate(grid),best=0;
15         boolean[][] visited=new boolean[grid.length][columns];
16         ArrayDeque<int[]> queue=new ArrayDeque<>();
17         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++) {
18             if(grid[r][c]!=1||visited[r][c])continue;
19             int area=0;visited[r][c]=true;queue.addLast(new int[]{r,c});
20             while(!queue.isEmpty()) {
21                 int[] cell=queue.removeFirst();area++;
22                 for(int[] d:DIRECTIONS) {
23                     int nr=cell[0]+d[0],nc=cell[1]+d[1];
24                     if(nr<0||nr>=grid.length||nc<0||nc>=columns||grid[nr][nc]!=1||visited[nr][nc])continue;
25                     visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});
26                 }
27             }
28             best=Math.max(best,area);
29         }
30         return best;
31     }
32     public static int baseline(int[][] grid) {
33         int columns=validate(grid),best=0;
34         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++)if(grid[r][c]==1) {
35             boolean[][] visited=new boolean[grid.length][columns];ArrayDeque<int[]> queue=new ArrayDeque<>();
36             visited[r][c]=true;queue.addLast(new int[]{r,c});int area=0;
37             while(!queue.isEmpty()) {
38                 int[] cell=queue.removeFirst();area++;
39                 for(int[] d:DIRECTIONS) {int nr=cell[0]+d[0],nc=cell[1]+d[1];if(nr>=0&&nr<grid.length&&nc>=0&&nc<columns&&grid[nr][nc]==1&&!visited[nr][nc]){visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});}}
40             }
41             best=Math.max(best,area);
42         }
43         return best;
44     }
45 }
46 

Highlight locates the relevant statement or block; one trace step may summarize several assignments.

Read the full static trace
  1. Begin a scan with no claimed land.

    A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

    source
    [[1,0],[0,1]]
    grid
    [[1,0],[0,1]]
    queue
    []
    visited
    [[false,false],[false,false]]
    area
    0
    best
    0
    seed
    null
    completed
    []
    phase
    "initial"
    current
    null
  2. Start one previously unclaimed component.

    Global visited ownership prevents recounting this component from another seed.

    source
    [[1,0],[0,1]]
    grid
    [[1,0],[0,1]]
    queue
    [[0,0]]
    visited
    [[true,false],[false,false]]
    area
    0
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "seed"
    current
    [0,0]
  3. Count one popped land coordinate.

    Queued cells are already claimed but contribute to area when popped. Source values remain unchanged.

    source
    [[1,0],[0,1]]
    grid
    [[1,0],[0,1]]
    queue
    []
    visited
    [[true,false],[false,false]]
    area
    1
    best
    0
    seed
    [0,0]
    completed
    []
    phase
    "visit"
    current
    [0,0]
  4. Finish the component before comparing its full area.

    An empty queue certifies complete component coverage. best is the largest finished component, not the number of islands.

    source
    [[1,0],[0,1]]
    grid
    [[1,0],[0,1]]
    queue
    []
    visited
    [[true,false],[false,false]]
    area
    1
    best
    1
    seed
    [0,0]
    completed
    [{"seed":[0,0],"area":1}]
    phase
    "component"
    current
    null
  5. Start one previously unclaimed component.

    Global visited ownership prevents recounting this component from another seed.

    source
    [[1,0],[0,1]]
    grid
    [[1,0],[0,1]]
    queue
    [[1,1]]
    visited
    [[true,false],[false,true]]
    area
    0
    best
    1
    seed
    [1,1]
    completed
    [{"seed":[0,0],"area":1}]
    phase
    "seed"
    current
    [1,1]
  6. Count one popped land coordinate.

    Queued cells are already claimed but contribute to area when popped. Source values remain unchanged.

    source
    [[1,0],[0,1]]
    grid
    [[1,0],[0,1]]
    queue
    []
    visited
    [[true,false],[false,true]]
    area
    1
    best
    1
    seed
    [1,1]
    completed
    [{"seed":[0,0],"area":1}]
    phase
    "visit"
    current
    [1,1]
  7. Finish the component before comparing its full area.

    An empty queue certifies complete component coverage. best is the largest finished component, not the number of islands.

    source
    [[1,0],[0,1]]
    grid
    [[1,0],[0,1]]
    queue
    []
    visited
    [[true,false],[false,true]]
    area
    1
    best
    1
    seed
    [1,1]
    completed
    [{"seed":[0,0],"area":1},{"seed":[1,1],"area":1}]
    phase
    "component"
    current
    null
  8. Return the documented value, changed-grid view, fresh result, or cloned graph view.

    Coordinates and object identities follow the problem-specific contract. Discovery histories are teaching views, not additional Java workspace.

    result
    1

Empty grid

Input: [] · Maximum island area: 0

Step 1 of 2: Begin a scan with no claimed land.

A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

Island area — component ownership and finished maximum

Phase: initial.

Unchanged source grid

No cells.

Coordinate queue — front at left; already claimed

Empty.

✓ = discovered land. Current component popped area: 0. Largest finished area: 0. Queued cells count toward area only when popped; the maximum updates after the component finishes. Water is 0 and land is 1; only orthogonal contact connects land.

The exact state table and static walkthrough below provide the same information without relying on color.

State after this step
VariableValue
source[]
grid[]
queue[]
visited[]
area0
best0
seednull
completed[]
phase"initial"
currentnull
See the affected Java block
 1 import java.util.*;
 2 public final class Solution {
 3     private static final int[][] DIRECTIONS = {{-1,0},{0,1},{1,0},{0,-1}};
 4     private static int validate(int[][] grid) {
 5         Objects.requireNonNull(grid,"grid");
 6         int columns=grid.length==0?0:grid[0]==null?-1:grid[0].length;
 7         for(int[] row:grid) {
 8             if(row==null||row.length!=columns)throw new IllegalArgumentException("nonrectangular grid");
 9             for(int value:row) if(value!=0&&value!=1)throw new IllegalArgumentException("invalid cell");
10         }
11         return columns;
12     }
13     public static int maxArea(int[][] grid) {
14         int columns=validate(grid),best=0;
15         boolean[][] visited=new boolean[grid.length][columns];
16         ArrayDeque<int[]> queue=new ArrayDeque<>();
17         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++) {
18             if(grid[r][c]!=1||visited[r][c])continue;
19             int area=0;visited[r][c]=true;queue.addLast(new int[]{r,c});
20             while(!queue.isEmpty()) {
21                 int[] cell=queue.removeFirst();area++;
22                 for(int[] d:DIRECTIONS) {
23                     int nr=cell[0]+d[0],nc=cell[1]+d[1];
24                     if(nr<0||nr>=grid.length||nc<0||nc>=columns||grid[nr][nc]!=1||visited[nr][nc])continue;
25                     visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});
26                 }
27             }
28             best=Math.max(best,area);
29         }
30         return best;
31     }
32     public static int baseline(int[][] grid) {
33         int columns=validate(grid),best=0;
34         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++)if(grid[r][c]==1) {
35             boolean[][] visited=new boolean[grid.length][columns];ArrayDeque<int[]> queue=new ArrayDeque<>();
36             visited[r][c]=true;queue.addLast(new int[]{r,c});int area=0;
37             while(!queue.isEmpty()) {
38                 int[] cell=queue.removeFirst();area++;
39                 for(int[] d:DIRECTIONS) {int nr=cell[0]+d[0],nc=cell[1]+d[1];if(nr>=0&&nr<grid.length&&nc>=0&&nc<columns&&grid[nr][nc]==1&&!visited[nr][nc]){visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});}}
40             }
41             best=Math.max(best,area);
42         }
43         return best;
44     }
45 }
46 

Highlight locates the relevant statement or block; one trace step may summarize several assignments.

Read the full static trace
  1. Begin a scan with no claimed land.

    A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

    source
    []
    grid
    []
    queue
    []
    visited
    []
    area
    0
    best
    0
    seed
    null
    completed
    []
    phase
    "initial"
    current
    null
  2. Return the documented value, changed-grid view, fresh result, or cloned graph view.

    Coordinates and object identities follow the problem-specific contract. Discovery histories are teaching views, not additional Java workspace.

    result
    0

Rows can have zero columns

Input: [[],[]] · Maximum island area: 0

Step 1 of 2: Begin a scan with no claimed land.

A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

Island area — component ownership and finished maximum

Phase: initial.

Unchanged source grid

No cells.

Coordinate queue — front at left; already claimed

Empty.

✓ = discovered land. Current component popped area: 0. Largest finished area: 0. Queued cells count toward area only when popped; the maximum updates after the component finishes. Water is 0 and land is 1; only orthogonal contact connects land.

The exact state table and static walkthrough below provide the same information without relying on color.

State after this step
VariableValue
source[[],[]]
grid[[],[]]
queue[]
visited[[],[]]
area0
best0
seednull
completed[]
phase"initial"
currentnull
See the affected Java block
 1 import java.util.*;
 2 public final class Solution {
 3     private static final int[][] DIRECTIONS = {{-1,0},{0,1},{1,0},{0,-1}};
 4     private static int validate(int[][] grid) {
 5         Objects.requireNonNull(grid,"grid");
 6         int columns=grid.length==0?0:grid[0]==null?-1:grid[0].length;
 7         for(int[] row:grid) {
 8             if(row==null||row.length!=columns)throw new IllegalArgumentException("nonrectangular grid");
 9             for(int value:row) if(value!=0&&value!=1)throw new IllegalArgumentException("invalid cell");
10         }
11         return columns;
12     }
13     public static int maxArea(int[][] grid) {
14         int columns=validate(grid),best=0;
15         boolean[][] visited=new boolean[grid.length][columns];
16         ArrayDeque<int[]> queue=new ArrayDeque<>();
17         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++) {
18             if(grid[r][c]!=1||visited[r][c])continue;
19             int area=0;visited[r][c]=true;queue.addLast(new int[]{r,c});
20             while(!queue.isEmpty()) {
21                 int[] cell=queue.removeFirst();area++;
22                 for(int[] d:DIRECTIONS) {
23                     int nr=cell[0]+d[0],nc=cell[1]+d[1];
24                     if(nr<0||nr>=grid.length||nc<0||nc>=columns||grid[nr][nc]!=1||visited[nr][nc])continue;
25                     visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});
26                 }
27             }
28             best=Math.max(best,area);
29         }
30         return best;
31     }
32     public static int baseline(int[][] grid) {
33         int columns=validate(grid),best=0;
34         for(int r=0;r<grid.length;r++)for(int c=0;c<columns;c++)if(grid[r][c]==1) {
35             boolean[][] visited=new boolean[grid.length][columns];ArrayDeque<int[]> queue=new ArrayDeque<>();
36             visited[r][c]=true;queue.addLast(new int[]{r,c});int area=0;
37             while(!queue.isEmpty()) {
38                 int[] cell=queue.removeFirst();area++;
39                 for(int[] d:DIRECTIONS) {int nr=cell[0]+d[0],nc=cell[1]+d[1];if(nr>=0&&nr<grid.length&&nc>=0&&nc<columns&&grid[nr][nc]==1&&!visited[nr][nc]){visited[nr][nc]=true;queue.addLast(new int[]{nr,nc});}}
40             }
41             best=Math.max(best,area);
42         }
43         return best;
44     }
45 }
46 

Highlight locates the relevant statement or block; one trace step may summarize several assignments.

Read the full static trace
  1. Begin a scan with no claimed land.

    A coordinate is claimed when enqueued, not when popped. Component area counts popped cells until the queue empties.

    source
    [[],[]]
    grid
    [[],[]]
    queue
    []
    visited
    [[],[]]
    area
    0
    best
    0
    seed
    null
    completed
    []
    phase
    "initial"
    current
    null
  2. Return the documented value, changed-grid view, fresh result, or cloned graph view.

    Coordinates and object identities follow the problem-specific contract. Discovery histories are teaching views, not additional Java workspace.

    result
    0

Test the contract

  1. Input: Empty or zero-column grid
    Output: 0

    No land vertices.

  2. Input: All water
    Output: 0

    No traversal seed.

  3. Input: Diagonal-only contact
    Output: 1 for two isolated ones

    Orthogonal contract.

  4. Input: 100,000 connected cells in a corridor
    Output: 100000

    Iterative traversal and int-safe area.

Common mistakes and counterexamples

Join diagonal land

Counterexample: The two ones in [[1,0],[0,1]] do not form area two.

Use the four declared directions.

Mark only after popping

Counterexample: Two parents can enqueue the same land coordinate and inflate work or counts.

Claim before enqueue.

Add all island sizes together

Counterexample: Disconnected land does not belong to one island.

Reset area at a new seed and retain the maximum.

Follow-ups

Return the winning component coordinates.

Define a deterministic tie rule and retain or reconstruct its members. Copying the current component on every improvement adds output/history work that must be counted.

Allow diagonal adjacency.

Change the direction set to eight neighbors and revise examples/tests. The ownership proof stays the same, but the component partition changes.

Process online land additions.

Use a disjoint-set structure with component sizes and an active-cell flag. Handle duplicate additions and distinguish dynamic updates from this static scan.

Related foundations

Keep practicing

AceYourInterviews · 2026-10-17 · Original teaching content and implementations authored for AceYourInterviews. Standard names do not imply company-frequency or external-platform equivalence claims.