Connected Cells in a Grid

  • + 0 comments
    def connectedCell(matrix):
        # Write your code here
        ones = []
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == 1:
                    ones.append((i, j))
        l = []
        while ones != []:
            one = ones.pop(0)
            ll = [one]
            m = 1
            n = 0
            while n != m:
                #count pre expansion
                m = len(ll)
                for one in ll:
                    i, j = one[0], one[1]
                    neighbors = [(i-1, j-1), (i-1, j), (i-1, j+1), (i, j-1), (i, j+1), (i+1, j-1), (i+1, j), (i+1, j+1)]
                    for neighbor in neighbors:
                        if neighbor in ones:
                            ones.remove(neighbor)
                            ll.append(neighbor)
                #count post expansion
                n = len(ll)
            l.append(len(ll))   
        return max(l)