Check if a matrix contains only unique connected components

Viewed 48

I am trying to write a program in python that will return true or false based on if a rectangular matrix contains only unique connected components. I have written a depth first search that checks all adjacent points to build out the connected components. But when I run it on larger data sets I get a stack overflow or hit the RecursionError: maximum recursion depth exceeded in comparison error.

For example give:

AAAABB
AAAABB
CCCCCC
CCCCAC

This would return True since there are two connected components containing the letter A. In the upper left corner and the individual A in the bottom right.

Here is my function:

def check_for_unique_components(matrix, n_cols, n_rows):
    visited = np.zeros((n_rows, n_cols))

    def valid_node(M, row, col, c, n, l):
        return ((row >= 0 and row < n) and (col >= 0 and col < l) and (M[row][col] == c and not visited[row][col]))

    def dfs(M, row, col, c, n, l):
        rowMoves = [-1, 0, 1, -1, 1, -1, 0, 1]
        colMoves = [-1, -1, -1, 0, 0, 1, 1, 1]

        visited[row][col] = True

        for k in range(8):
            if (valid_node(M, row+rowMoves[k], col + colMoves[k], c, n, l)):
                dfs(M, row+rowMoves[k], col+colMoves[k], c, n, l)

    def connectedComponenets(M):
        visited_blocks = set()
        n = len(M)
        l = len(M[0])

        for i in range(n):
            for j in range(l):
                if (not visited[i][j]):
                    c = M[i][j]
                    dfs(M, i, j, c, n, l)
                    if c in visited_blocks:
                        return True
                    else:
                        visited_blocks.add(c)
        return False

    return(connectedComponenets(cell_matrix))

The function runs an adjacency search for each value in the matrix and stores each letter that has already been seen in a connected component.

0 Answers
Related