-
Notifications
You must be signed in to change notification settings - Fork 0
/
FloydWarshall.py
74 lines (62 loc) · 1.86 KB
/
FloydWarshall.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
INF = float('inf')
def PrintPath(path, s, f):
if f == s:
print(f, end=" ")
return
if path[s][f] == -1:
print("NO PATH", end=' ')
return
PrintPath(path, s, path[s][f])
print(f, end=" ")
def PrintSolution(graph, dist, V):
for i in range(V):
for j in range(V):
if i != j:
print("{} -> {}".format(i, j), end='\n')
PrintPath(path, i, j)
print()
if path[i][j] != -1:
print("Total length: {}".format(dist[i][j]))
def FloyWarshall(graph, dist, path, V):
# Make dist matrix
for i in range(V):
for j in range(V):
dist[i][j] = graph[i][j]
if graph[i][j] != INF and i != j:
path[i][j] = i
else:
path[i][j] = -1
# Find shortest path between pairs of nodes
for k in range(V):
for i in range(V):
if dist[i][k] == INF:
continue
for j in range(V):
if dist[k][j] != INF and dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
path[i][j] = path[k][j]
for i in range(V):
if dist[i][i] < 0: return False
return True
if __name__ == '__main__':
V = int(input())
graph = [[None for i in range(V)] for j in range(V)]
dist = [[None for i in range(V)] for j in range(V)]
path = [[None for i in range(V)] for j in range(V)]
for i in range(V):
line = list(map(int, input().split()))
for j in range(V):
graph[i][j] = INF if line[j] == 0 and i != j else line[j]
if FloyWarshall(graph, dist, path, V):
PrintSolution(path, dist, V)
else:
print("Graph contains negative weight cycle")
'''
6
0 1 0 0 0 0
0 0 5 -2 0 7
0 0 0 0 0 -1
2 0 -1 0 4 0
0 0 0 3 0 0
0 0 0 0 1 0
'''