[Leetcode] Max Area of Island 最大島嶼面積

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.code

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)遞歸

Example 1:leetcode

[[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:get

[[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.io

深度優先搜索

思路

該題基本上就是Number of Islands的變形題,惟一的區別是在Number of Islands中咱們只須要將搜索到的陸地置爲0,保證其不會再被下次探索所用就好了。但這題多了一要求就是要同時返回島嶼的面積。那麼最簡單的方式就是在遞歸的時候,每一個搜索到的格子都將自身的面積1,加上四個方向搜索出來的延伸面積都加上,再返回給調用遞歸的那個格子做爲延伸面積使用,這樣一直返回到島嶼的起始格子時,面積之和就是島嶼的總面積了。class

代碼

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
}
相關文章
相關標籤/搜索