Problem
You are given an m x n
binary matrix grid
. An island is a group of 1
‘s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1
in the island.
Return the maximum area of an island in grid
. If there is no island, return 0
.
Example 1:
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]] |
Example 2:
1 | Input: grid = [[0,0,0,0,0,0,0,0]] |
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either0
or1
.
Analysis
这是一道二维矩阵遍历的题目,基本的思想还是DFS。但这次要计算的并不是从某个点到某个点的路径,而是面积,这是有不同的。计算路径时,我们只需要返回一个最大或最小的长度,但是计算面积时,需要把面积加起来。
每个格到四个方向移动的套路相信大家都很熟悉了,走过的地方也要标记一下,不能重复访问。然后每个格子把四个方向DFS的结果相加,最后加上1(自己当前这格所占的面积)。然后我们全局维护一个最大的面积即可。
Solution
无
Code
1 | class Solution { |
Summary
这道题虽然意思上稍作修改,从路径变成了面积,但是整体的算法思路是一样的。这道题目的分享到这里,感谢你的支持!