Python iterative solution


  • 0
    T

    I implemented the iterative solution for python using stack as following,

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

Log in to reply
 

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