求矩阵中具有相同值的相邻元素(垂直或水平)的数目

2024-04-26 00:12:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手。我试图找到相邻元素的数量具有相同的值。 如果符号数大于等于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个

你能给我一个主意吗


Tags: 元素数量编程符号matrix主意新手
1条回答
网友
1楼 · 发布于 2024-04-26 00:12:27

基本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

相关问题 更多 >