DFS: Connected Cell in a Grid

  • + 0 comments

    Python

    def neighborhood(i, j):
        return [(i+1, j), (i-1, j), (i, j+1), (i, j-1), (i+1, j+1), (i-1, j-1), (i-1, j+1), (i+1, j-1)]
    
    def maxRegion(grid):
        largest_region_size = 0
        visited = set()
        for i in range(len(grid)-1):
            for j in range(len(grid[0])):
                if (i, j) in visited or grid[i][j] == 0:
                    continue
                region_size = 1
                visited.add((i, j))
                stack = neighborhood(i, j)
                while stack:
                    curr = stack.pop()
                    if curr in visited or curr[0] < 0 or curr[1] < 0:
                        continue
                    try:
                        if grid[curr[0]][curr[1]] == 0:
                            continue
                    except:
                        continue
                    visited.add((curr[0], curr[1]))
                    region_size += 1
                    stack.extend(neighborhood(curr[0], curr[1]))
                largest_region_size = max(largest_region_size, region_size)
                    
                
        return largest_region_size