Largest Landmass
EasyGraphsFree
Problem
A land registry stores a region as a binary matrix grid: 1 is land, 0 is water. An island is a group of land cells connected horizontally or vertically, and its area is the number of cells in it.
Return the area of the largest island, or 0 if there is no land.
Example 1
- Input:
- grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,1]]
- Output:
- 4
The top-left island has area 3; the island made of (1,3), (2,2), (2,3) and (3,3) has area 4.
Example 2
- Input:
- grid = [[0,0],[0,0]]
- Output:
- 0
Constraints
- 1 ≤ rows, cols ≤ 100
- grid[r][c] is 0 or 1
Hint
Show the first hint
This is island counting with one extra number to track per island.
Walkthrough
How to approach it
01Clarify before coding
- Is connectivity 4-directional? Yes.
- May I modify the grid? Yes here; otherwise use a visited matrix.
- What if there is no land? Return 0.
02Brute force
From every land cell, run a fresh flood fill with its own visited set and record the size; take the maximum.
Cost: Each fill is O(r · c) and there can be r · c starting cells: O((r · c)²), about 10^8 for a fully-land 100 × 100 grid.
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.