Search code examples
pythonalgorithmmatrixadjacency-matrix

Find the number of (vertically or horizontally) adjacent elements of a matrix have the same value


I am new to programming. I am trying to find number of adjacent elements have the same value. Printing if the number of symbols is 8 or greater. Example:

matrix = [
    [2, 1, 5, 7, 4, 4],
    [2, 2, 8, 4, 4, 5],
    [0, 2, 1, 5, 4, 4],
    [1, 2, 4, 2, 4, 4],
    [2, 2, 2, 2, 8, 9]
]

Output: There are 10 of symbols 2 and 8 of symbol 4.

Can you give me an idea?


Solution

  • A basic depth-first search traverse will help on this problem:

    matrix = [
        [2, 1, 5, 7, 4, 4],
        [2, 2, 8, 4, 4, 5],
        [0, 2, 1, 5, 4, 4],
        [1, 2, 4, 2, 4, 4],
        [2, 2, 2, 2, 8, 9]
    ]
    
    ROW = len(matrix)
    COL = len(matrix[0])
    
    dirs = [
        (0, 1),
        (0, -1),
        (1, 0),
        (-1, 0)
    ]
    
    def dfs(row, col, vis):
        if vis[row][col]:
            return 0
        vis[row][col] = True
        count = 1
        for dir in dirs:
            r, c = row + dir[0], col + dir[1]
            if r >= 0 and r < ROW and c >= 0 and c < COL and matrix[row][col] == matrix[r][c]:
                count = count + dfs(r, c, vis)
        return count
    
    def calc_occurance():
        for r in range(ROW):
            for c in range(COL):
                vis = [[False] * COL for _ in range(ROW)]
                print(f"symbol {matrix[r][c]} at ({r}, {c}), occurance:", dfs(r, c, vis))
    
    calc_occurance()
    

    output:

    symbol 2 at (0, 0), occurrence: 10
    symbol 1 at (0, 1), occurrence: 1
    symbol 5 at (0, 2), occurrence: 1
    symbol 7 at (0, 3), occurrence: 1
    symbol 4 at (0, 4), occurrence: 8
    symbol 4 at (0, 5), occurrence: 8
    symbol 2 at (1, 0), occurrence: 10
    symbol 2 at (1, 1), occurrence: 10
    symbol 8 at (1, 2), occurrence: 1
    symbol 4 at (1, 3), occurrence: 8
    symbol 4 at (1, 4), occurrence: 8
    symbol 5 at (1, 5), occurrence: 1
    symbol 0 at (2, 0), occurrence: 1
    symbol 2 at (2, 1), occurrence: 10
    symbol 1 at (2, 2), occurrence: 1
    symbol 5 at (2, 3), occurrence: 1
    symbol 4 at (2, 4), occurrence: 8
    symbol 4 at (2, 5), occurrence: 8
    symbol 1 at (3, 0), occurrence: 1
    symbol 2 at (3, 1), occurrence: 10
    symbol 4 at (3, 2), occurrence: 1
    symbol 2 at (3, 3), occurrence: 10
    symbol 4 at (3, 4), occurrence: 8
    symbol 4 at (3, 5), occurrence: 8
    symbol 2 at (4, 0), occurrence: 10
    symbol 2 at (4, 1), occurrence: 10
    symbol 2 at (4, 2), occurrence: 10
    symbol 2 at (4, 3), occurrence: 10
    symbol 8 at (4, 4), occurrence: 1
    symbol 9 at (4, 5), occurrence: 1