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

给一个二维数组,0表示空,1表示岛,上下左右如果有1相邻,那么属于同一个岛,问1最多的岛的1个个数是多少。

就是求最大联通快1的个数。dfs或者bfs都可以。

class Solution(object):
    def maxAreaOfIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        n = len(grid)
        m = len(grid[0])
        vis = []
        for i in range(n):
            vis.append([0] * m)
        def dfs(grid, vis, i, j, n, m):
            dires = [[0, 1], [0, -1], [1, 0], [-1, 0]]
            vis[i][j] = 1
            ans = 1
            for dire in dires:
                x = i + dire[0]
                y = j + dire[1]
                if x < n and x >= 0 and y < m and y >= 0 and grid[x][y] == 1 and vis[x][y] == 0:
                    ans += dfs(grid, vis, x, y, n, m)
            return ans
            
        ans = 0
        for i in range(n):
            for j in range(m):
                if vis[i][j] == 0 and grid[i][j] == 1:
                    ans = max(ans, dfs(grid, vis, i, j, n, m))
        return ans

 

posted @ 2020-07-22 13:21  whatyouthink  阅读(77)  评论(0编辑  收藏  举报