iq.lab
Python starts when a code cell comes near or you run one
mediumDepth-first search target 25 min

Largest island

A map is a grid of numbers: 1 is land and 0 is water. Two land cells are on the same island when you can walk from one to the other by stepping up, down, left or right, only on land. Diagonal steps do not count. An island's area is how many land cells it holds.

Return the largest area of any island, or 0 if the map has no land.

Example 1
Inputgrid = [[1, 1, 0, 0], [0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 0]]Output4

Writing cells as (row, column), the island on the right is (1, 3), (2, 3), (2, 2) and (3, 2): area 4. The island at the top left has area 3, and (2, 0) alone has area 1.

Example 2
Inputgrid = [[0, 0], [0, 0]]Output0

There is no land, so there is no island.

Example 3
Inputgrid = [[1, 0, 1, 1, 1]]Output3

The three 1s at the end form the largest island.

Constraints
  • 1 ≤ number of rows, number of columns ≤ 50

  • Every cell is 0 or 1.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.