gpt4 book ai didi

python - Warshall 的传递闭包算法(Python)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:12:50 26 4
gpt4 key购买 nike

我正在编写一个程序,该程序使用 Warshall 算法来查找表示关系的矩阵的传递闭包。这是伪代码中算法的链接:http://people.cs.pitt.edu/~adamlee/courses/cs0441/lectures/lecture27-closures.pdf (第 21 页)。

def warshall(a):

assert (len(row) == len(a) for row in a)
n = len(a)
for k in range (1,n):
for i in range (1,n):
for j in range (1,n):
a[i][j] = a[i][j] or (a[i][k] and a[k][j])


return M

print warshall([[0,0,0,1],[1,0,1,0],[1,0,0,1],[0,0,1,0]])

我应该得到 [[1,0,1,1],[1,0,1,1],[1,0,1,1],[1,0,1,1]]

正在获取 [[0,0,0,1],[1,0,1,1],[1,0,1,1],[0,0,1,1]]

最佳答案

在讲座中,索引是从 1 到 n,但在这里,你必须从 0 到 n-1,所以 range 函数必须是 range(0,n) 或者,更简洁地 range(n) (另外,它是 return a,而不是 M)

def warshall(a):
assert (len(row) == len(a) for row in a)
n = len(a)
for k in range(n):
for i in range(n):
for j in range(n):
a[i][j] = a[i][j] or (a[i][k] and a[k][j])
return a

关于python - Warshall 的传递闭包算法(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com