Skip to content

Largest Island Area

Easy#flood-fill#dfs#grid-traversal~15 min

The mission

Problem

A map is a grid of 0s (water) and 1s (land). An island is a group of land cells connected up, down, left or right; diagonal neighbours do not connect. The area of an island is its number of cells. Return the area of the largest island, or 0 if there is no land.

Examples

Input:  grid = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 0]]
Output: 4
Why:    the top-left island has 3 cells and the one on the right has 4
Input:  grid = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
Output: 1
Why:    diagonal cells do not join, so there are five islands of one cell
Input:  grid = [[0, 0], [0, 0]]
Output: 0
Why:    edge case, no land at all

Hints

0 / 3

Target time
O(rows · cols)
Target space
O(rows · cols)

Constraints

  • cells are 1 (land) or 0 (water)

Stuck on the idea rather than the code? Number of Islands covers it.

Python 3Ctrl+Enter runs
Custom test case