[英]Find all paths of length 2 in a graph
我试图创建一种算法来查找所有长度为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
您正在计算步行,其中包括步行6-7-6(不是P2)
该讨论可能会有所帮助: https : //math.stackexchange.com/questions/1890620/finding-path-lengths-by-the-power-of-adjacency-matrix-of-an-undirected-graph
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.