【问题标题】:Find the number of (vertically or horizontally) adjacent elements of a matrix have the same value查找矩阵中具有相同值的(垂直或水平)相邻元素的数量
【发布时间】:2020-04-07 10:11:22
【问题描述】:

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

你能给我一个想法吗?

【问题讨论】:

  • 您可能正在寻找类似洪水填充算法的东西。

标签: python algorithm matrix adjacency-matrix


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 2012-09-10
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2015-05-20
    • 2020-10-16
    • 2021-05-17
    相关资源
    最近更新 更多