Max Area of Island Without Changing the Grid
Problem statement
You are given a grid grid 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 its number of cells.
Return the largest island area in the grid, or 0 if the grid has no land.
Your function must not change grid. Keep track of the cells you have already visited in your own structure. The judge checks only the returned area.
Follow-up: if you used depth-first search, can you also solve it with breadth-first search?
Function
maxAreaOfIsland(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0,0,1],[0,1,0,1,1],[0,0,0,0,1],[1,0,1,0,0]]return = 4There are four islands. The top-left island has the cells (0, 0), (0, 1) and (1, 1), so its area is 3. The right island has (0, 4), (1, 3), (1, 4) and (2, 4), so its area is 4. The cells (3, 0) and (3, 2) are single-cell islands. The largest area is 4.
Example 2
grid = [[0,0],[0,0]]return = 0The grid has no land, so the answer is 0.
Example 3
grid = [[1,0,1],[0,1,0],[1,0,1]]return = 1Every land cell touches the others only at corners. Diagonal neighbors are not connected, so there are five islands of area 1 and the answer is 1.
Constraints
1 <= grid.length <= 501 <= grid[i].length <= 50- Every row has the same length.
grid[i][j]is0or1.