Example 1
- Input
- grid = [[1,1,0],[0,1,0],[1,0,1]]
- Output
- 3
Cells (0,0), (0,1) and (1,1) connect through shared sides. The bottom corners touch that group only diagonally, so each has area 1 and the maximum is 3.
Given a binary grid of land and water, find the cell count of the largest landmass connected horizontally or vertically. Grids without land score zero.
You are given an m x n binary matrix grid where 1 is land and 0 is water.
An island is a group of 1s connected horizontally or vertically, and its area is its cell count. Return the largest island area, or 0 when there is no land.
m == grid.lengthn == grid[i].length1 <= m, n <= 50grid[i][j] is 0 or 1.Cells (0,0), (0,1) and (1,1) connect through shared sides. The bottom corners touch that group only diagonally, so each has area 1 and the maximum is 3.
No land cell exists, so the maximum area is zero.
The only cell is land, so it forms one island of area 1 even though every neighbor lies outside the grid.
The land around rows 3-5 near column 8 links six cells, beating the islands of size 5, 4 and 1.
An island is a connected component of land cells: starting at any of its cells and following only horizontal or vertical land neighbors reaches exactly that island. In Example 1, (0,0), (0,1) and (1,1) make a component of area 3, while (2,0) and (2,2) each stand alone. Count cells during a flood fill and keep the largest count. Remembering discoveries across the outer scan prevents measuring the same island again.
Reveal Flood Per Cell: intuition, complexity, and code
Grid flood problems reward settling each cell once; sinking land or a global visited set turns repeated island walks into a single linear sweep.