733. Algorithem_Max Area of Island
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]] |
解法
和 FloodFill 算法类似,只不过这里不是把相邻的改为一样的颜色,而是计算相邻的1的个数。解法是:遍历数组,如果当前元素为1,则计算这个元素周边的1的个数——通过递归,获取相邻元素的值,为1的个数相加,并且把当前元素改为0,避免重复计算。
代码如下:
1 |
|