Max Area of Island
MediumGraphs
You are given an m x n grid of integers where 1 is land and 0 is water. An island is a group of land cells connected horizontally or vertically (cells that touch only at a corner are not connected). The area of an island is the number of land cells in it.
Return the area of the largest island in grid, or 0 if there is no land at all. You may modify grid while solving.
Example 1
- Input:
- grid = [[0, 1, 1, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [1, 1, 0, 0, 1]]
- Output:
- 4
- Explanation
- There are three islands: three cells at the top (rows 0-1, columns 1-2), three cells in the bottom-left corner, and four cells on the right side (column 4 in rows 1-3 plus the cell at row 2, column 3). The largest has area 4.
Example 2
- Input:
- grid = [[1, 0], [0, 1]]
- Output:
- 1
- Explanation
- The two land cells touch only diagonally, so they are separate islands of area 1 each.
Example 3
- Input:
- grid = [[0, 0, 0]]
- Output:
- 0
- Explanation
- There is no land, so the answer is 0.
Constraints
m == grid.length,n == grid[i].length1 <= m, n <= 50grid[i][j]is0or1