1. 程式人生 > 實用技巧 >695. Max Area of Island

695. Max Area of Island

Given a non-empty 2D arraygridof 0's and 1's, anislandis a group of1'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