python - 在图中查找所有长度为 2 的路径

标签 python algorithm graph path-finding

我试图创建一个算法来查找所有长度为 2 的路径,但它似乎无法正常工作:

input_split = input().split(' ')
node_count = int(input_split[0])
input_count = int(input_split[1])
items = np.zeros((node_count, node_count), dtype=np.int32) # matrix of adjacency
for j in range(input_count):
    split = input().split(' ')
    x = int(split[0]) - 1 # convert 1 based coordinates to 0 based
    y = int(split[1]) - 1
    items[x][y] = 1
    items[y][x] = 1
result = np.linalg.matrix_power(items, 2)
result_sum = int(np.sum(result) / 2) # reverse paths are counted only once
print(result_sum)

示例输入:

6 7
1 2
2 3
3 1
2 4
4 5
5 6
6 2

结果应该是 11,但它打印出 18。

最佳答案

计算邻接矩阵的平方时,您的方向是正确的。取幂后,您将得到如下所示的结果矩阵:

[[2 1 1 1 0 1]
 [1 4 1 0 2 0]
 [1 1 2 1 0 1]
 [1 0 1 2 0 2]
 [0 2 0 0 2 0]
 [1 0 1 2 0 2]]

首先,您需要从该矩阵中排除所有对角线条目,因为这些条目表示不是路径的行走,因为它们的起始节点和结束节点相同。请注意,对于长度 2,这是节点重复的唯一方式。

由于对称性,其他条目只需计算一次。所以只看矩阵的右上三角。

一种方法是:

result_sum = 0
for i in range(input_count - 1):
    for j in range(i + 1, input_count - 1):
        result_sum += result[i][j]
print(result_sum) # prints 11

更多 Pythonic 方式,使用 numpy.trace() 的单行代码:

result_sum = (np.sum(result) - np.trace(result)) // 2

关于python - 在图中查找所有长度为 2 的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290045/

相关文章:

Python while 循环不会退出(初学者)

algorithm - 证明问题的NP完全性

algorithm - 求任意 N 个顶点之间所有路径的图算法

c - 找到第一个回文单词的开头

javascript - 如何使用多个字符串数据绘制谷歌折线图

MATLAB 直方图问题

python - 英特尔与 AMD 对运行 python 有影响吗?

python - 如何在 Windows 10 上为嵌入式 python 设置 virtualenv

python - Django ModelChoiceField 查询集的自定义顺序

algorithm - 为什么这个修剪是由我的程序完成的?