-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloydWarshall.py
69 lines (63 loc) · 1.96 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
import time
def floydWarshall(G, s, dest):
inicio = time.time()
print("\n")
print("Processando . . .")
dist = [[0 for x in range(len(G))] for x in range(len(G))]
pred = [[0 for x in range(len(G))] for x in range(len(G))]
for i in range(len(G)):
for j in range(len(G)):
if i == j:
dist[i][j] = 0
pred[i][j] = None
elif G[i][j] != 0:
dist[i][j] = G[i][j]
pred[i][j] = i
else:
dist[i][j] = float("inf")
pred[i][j] = None
#TESTES
# for i in range(len(G)):
# for j in range(len(G)):
# print(dist[i][j], " ", end="")
# print()
#
# print("\n")
# for i in range(len(G)):
# for j in range(len(G)):
# print(pred[i][j], " ", end="")
# print()
for k in range(len(G)):
for i in range(len(G)):
for j in range(len(G)):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
pred[i][j] = pred[k][j]
#imprimir as duas matrizes
# for i in range(len(G)):
# for j in range(len(G)):
# print(dist[i][j], " ", end="")
# print()
#
# print("\n")
# for i in range(len(G)):
# for j in range(len(G)):
# print(pred[i][j], " ", end="")
# print()
if dest < len(dist) and dest >= 0 and s < len(dist) and s >= 0:
caminho = []
caminho.append(dest)
custo = dist[s][dest]
if pred[s][dest] != None:
while dest != s:
caminho.append(pred[s][dest])
dest = pred[s][dest]
else:
print("Não existe caminho para o vertice escolhido!")
pass
fim = time.time()
print("Caminho: ",caminho[::-1])
print("Custo: ", custo)
print("Tempo", fim - inicio, "s")
else:
print("Erro!")