#695

Max Area of Island

pupil · 505 · lc medium +27 · verified · 73.8% accepted · 10,582 likes · top 84%

Description

You are given an m x n binary matrix grid where 1 represents land and 0 represents water. An island is a group of land cells connected 4-directionally. The grid boundary is entirely surrounded by water.

Find and return the maximum area (number of land cells) among all islands. Return 0 if no islands exist.

Example 1:

Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.

Example 2:

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

Code

1
2
3