Leetcode #695. Max Area of Island

题目

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.

题意

给出一个非空的二维数组里面填着0/1,然后你需要找到一个最大连通块,就是从这个区域块内的元素能任意走到这个区域块的其他元素。

想法

这道题首先就要注意到它最大的特点就是要求连通,需要每一个能走到另外一个,那么其实就是说明如果是连通的那么如果当前是1它就能通过它的四邻域找到和它同个连通块的方格,以此一直走下去,这个就有点像走很经典的迷宫问题,然后你把0看成墙,1看成道路,现在不同的是你可以从任意一个点出发看要找到一个最大能走动的区域。类比这道题,这个题大家也就知道能用BFS进行解答,过程就跟传染病毒一样。在递归的过程中以碰到墙放弃当前的搜索,不然就把这个格子的四邻域都走个遍,每次回传当前格子出发能碰到的最大区域。这个过程有一个需要注意的是不能重复搜索,我的做法就是直接走过我就置0,或者再开一个标记数组/矩阵也行。

class Solution(object):
    def maxAreaOfIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        def bfs(grid, i, j):
            if grid[i][j] == 1:
                grid[i][j] = 0
                result = 1
                if i+1<len(grid):  #判断下边的格子是不是墙
                    result+=bfs(grid, i+1, j)
                if i-1>=0:  #判断上边的格子是不是墙
                    result+=bfs(grid, i-1, j)
                if j+1<len(grid[0]):  #判断右边的格子是不是墙
                    result+=bfs(grid, i, j+1)
                if j-1>= 0:  #判断左边的格子是不是墙
                    result+=bfs(grid, i, j-1)
                return result
            else:
                return 0
        result = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:  #选择没走过的起点
                    result = max(bfs(grid, i, j),result)
        return result
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值