DFS: Connected Cell in a Grid

  • + 0 comments

    Here is my Python3 solution

    def maxRegion(grid):
        def dfs(grid, row, col):
    
            grid[row][col] = 0
            visited.add((row,col))
            cur = 1
            # 8 directions
            steps = [(row-1,col-1), (row-1,col), (row-1,col+1),
                    (row,col-1), (row,col+1),
                    (row+1,col-1), (row+1,col), (row+1,col+1)]
    								
            # Check if over edge and visited
            for r, c in steps:
                if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 1 and grid[r][c] not in visited:
                    cur += dfs(grid, r, c)
            
            return cur
            
        ans = 0
        visited = set()
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    res = dfs(grid, i, j)
                    ans = max(ans, res)
        
        return ans