easy python


  • 6
    F
        def maxAreaOfIsland(self, grid):
            m, n = len(grid), len(grid[0])
    
            def dfs(i, j):
                if 0 <= i < m and 0 <= j < n and grid[i][j]:
                    grid[i][j] = 0
                    return 1 + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i + 1, j) + dfs(i, j - 1)
                return 0
    
            areas = [dfs(i, j) for i in range(m) for j in range(n) if grid[i][j]]
            return max(areas) if areas else 0

  • 0
    L

    @fhqplzj Very clear. Thank you for the idea to send grid[i][j] into 0, when it's been explored.


  • 0
    S

    nice soln!
    maybe using max can save some space:

    maximum = 0
    ...
    for i in xrange (m):
        for j in xrange(n):
             if grid[i][j]:
                maximum = max(dfs(i,j),maximum)
    return maximum
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.