Max Area of Island
Medium · Graphs
You are given a grid of 0s and 1s representing water and land. An island is a group of 1 cells connected horizontally or vertically (not diagonally). Return the area, in number of cells, of the largest island in the grid. If there are no land cells at all, return 0.
Examples
Input: grid = [[0,0,1,0],[0,1,1,0],[0,0,0,1]]
Output: 3
Why: The largest connected group of 1s (up/down/left/right) has 3 cells, in the middle rows.
Input: grid = [[0,0,0],[0,0,0]]
Output: 0
Why: There are no cells with value 1, so the largest island has area 0.
Input: grid = [[1,1],[1,1]]
Output: 4
Why: All four cells are 1 and connected, forming a single island of area 4.
Constraints
1 <= grid.length, grid[0].length <= 50, grid[i][j] is either 0 or 1
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Max Area of Island. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.