oneby7

Graphs Grids as graphs

436. Max Area of Island

Medium

You are given a map as a grid of integers, grid, with m rows and n columns. A cell that holds 1 is land, and a cell that holds 0 is water.

An island is a group of land cells joined by steps up, down, left or right. Two land cells that touch only at a corner are not joined. Everything outside the grid is water. The area of an island is the number of land cells in it.

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

Example 1

110001100111001001111010011011

Input: grid = [[1, 1, 0, 0, 0, 1], [1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1], [1, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 1]]

Output: 6

Explanation: The four islands have areas 3 (top left), 5 (top right), 6 (bottom left) and 3 (bottom right). The land at row 1, column 3 touches the 6-cell island only at a corner, so the two stay apart.

Example 2

000000

Input: grid = [[0, 0, 0], [0, 0, 0]]

Output: 0

Explanation: There is no land, so there is no island.

Example 3

1111110001101011000111111

Input: grid = [[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]]

Output: 16

Explanation: The ring of 16 land cells is one island. The water inside it adds nothing to its area. The cell in the middle is a second island, with area 1.

Check your understanding

Work out the answer for this input before you write any code.

grid = [[1, 1, 0, 1], [0, 1, 0, 1], [1, 0, 0, 1], [1, 1, 0, 1]]

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 300
  • grid[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.