Python iterative solution


  • 0
    K

    Try to avoid recursion if possible

    class Solution:
        def maxAreaOfIsland(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            max_y = len(grid)
            max_x = len(grid[0])
            result = 0
            for y in range(max_y):
                for x in range(max_x):
                    if grid[y][x] == 1:
                        queue = [(y, x)]
                        local_max = 0
                        while queue:
                            point = queue.pop()
                            if 0 <= point[0] < max_y and 0 <= point[1] < max_x and grid[point[0]][point[1]] == 1:
                                grid[point[0]][point[1]] = 0
                                local_max += 1
                                queue.append((point[0] + 1, point[1]))
                                queue.append((point[0] - 1, point[1]))
                                queue.append((point[0], point[1] + 1))
                                queue.append((point[0], point[1] - 1))
                        result = max(result, local_max)
            return result
    

Log in to reply
 

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