查找矩阵的(垂直或水平)相邻元素具有相同值的数量

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

我是编程新手。我试图找到具有相同值的相邻元素的数量。 如果符号数为 8 或更大,则打印。 示例:

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]
]

输出:符号2有10个,符号4有8个。

你能给我个主意吗?

一个基本的 depth-first search 遍历将有助于解决这个问题:

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()

输出:

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