Solution 1

  • TimeO(m * n)
  • SpaceO(m * n)

where, m is number of rows, and n is number of columns
Solved in 10 mins, all by yourself! Good job!

Python
class Solution:
    '''
    Time Complexity: O(m * n)
    Space Complexity: O(m * n)
    where, m is number of rows, and n is number of columns
    Solved in 10 mins, all by yourself! Good job!
    '''
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        maxArea = 0
        def dfs(i,j):
            if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:
                return 0
            
            grid[i][j] = 0

            # val = 1 + dfs(i+1,j) + dfs(i-1,j) + dfs(i,j+1) + dfs(i,j-1) # What you wrote originally, vs negligible optimization
            # nonlocal maxArea
            # maxArea = max(maxArea, val)
            return 1 + dfs(i+1,j) + dfs(i-1,j) + dfs(i,j+1) + dfs(i,j-1) # return val
        
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                maxArea = max(maxArea, dfs(i,j)) # dfs(i,j)
        
        return maxArea
Leet Code/python.py · L2424–2449