[Leetcode] Max Area of Island 最大岛屿面积

37次阅读

共计 1402 个字符,预计需要花费 4 分钟才能阅读完成。

Max Area of Island
最新更新请见:https://yanjia.me/zh/2019/02/…

Given a non-empty 2D array grid of 0’s and 1’s, 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.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[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]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.Note: The length of each dimension in the given grid does not exceed 50.

深度优先搜索
思路
该题基本上就是 Number of Islands 的变形题,唯一的区别是在 Number of Islands 中我们只需要将搜索到的陆地置为 0,保证其不会再被下次探索所用就行了。但这题多了一要求就是要同时返回岛屿的面积。那么最简单的方式就是在递归的时候,每个搜索到的格子都将自身的面积 1,加上四个方向搜索出来的延伸面积都加上,再返回给调用递归的那个格子作为延伸面积使用,这样一直返回到岛屿的起始格子时,面积之和就是岛屿的总面积了。
代码
Go
func maxAreaOfIsland(grid [][]int) int {
maxArea := 0
for i := range grid {
for j := range grid[i] {
area := measureIsland(grid, i, j)
if area > maxArea {
maxArea = area
}
}
}
return maxArea
}

func measureIsland(grid [][]int, x, y int) int {
if grid[x][y] == 0 {
return 0
}
area := 1
grid[x][y] = 0
if x > 0 {
area += measureIsland(grid, x-1, y)
}
if x < len(grid)-1 {
area += measureIsland(grid, x+1, y)
}
if y > 0 {
area += measureIsland(grid, x, y-1)
}
if y < len(grid[0])-1 {
area += measureIsland(grid, x, y+1)
}
return area
}

正文完
 0