Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在图中查找长度为2的所有路径_Python_Algorithm_Graph_Path Finding - Fatal编程技术网

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

Python 在图中查找长度为2的所有路径,python,algorithm,graph,path-finding,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): sp

我尝试创建一个算法来查找长度为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。

您正在计算行走,其中包括行走6-7-6(不是P2)

这一讨论可能有助于:

您正在计算行走,包括行走6-7-6(不是P2)

这一讨论可能有助于:

计算邻接矩阵的平方时,您的思路是正确的。求幂后,您将得到如下结果矩阵:

[[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
使用
numpy.trace()


计算邻接矩阵的平方时,您的思路是正确的。求幂后,您将得到如下结果矩阵:

[[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
使用
numpy.trace()