[英]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.