Skip to content

Commit 44c4435

Browse files
authored
Adicionando Floyd-Warshall
1 parent da0c483 commit 44c4435

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/python/floyd-warshall.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from math import inf
2+
3+
def gerar_matriz (n_linhas, n_colunas):
4+
return [[0]*n_colunas for _ in range(n_linhas)]
5+
6+
def imprime(matriz, vertices):
7+
print(' ', end='')
8+
for i in range(vertices):
9+
print(" ",i + 1,end='')
10+
print('')
11+
for i in range(vertices):
12+
print(i + 1, matriz[i])
13+
14+
def floyd_warshall(matriz, vertices):
15+
dist = gerar_matriz(vertices, vertices)
16+
# inicializando a matriz com infinito nas diagonais e as distancias das arestas
17+
for i in range(vertices):
18+
for j in range(vertices):
19+
if(i != j):
20+
if(matriz[i][j] != 0):
21+
dist[i][j] = matriz[i][j]
22+
else:
23+
dist[i][j] = inf
24+
else:
25+
dist[i][i] = inf
26+
# Floyd-Warshal
27+
for k in range(vertices):
28+
for i in range(vertices):
29+
for j in range(vertices):
30+
Dist = inf
31+
if(dist[i][k] != inf or dist[k][j] != inf):
32+
Dist = dist[i][k] + dist[k][j]
33+
34+
if(i != j and Dist != inf and Dist < dist[i][j]):
35+
dist[i][j] = Dist
36+
# printando o resultado
37+
print('Matriz de distâncias')
38+
imprime(dist, vertices)
39+
40+
def main():
41+
grafo = [[0,3,4,0],[0,0,0,5],[0,0,0,3],[8,0,0,0]]
42+
vertices = 4
43+
floyd_warshall(grafo, vertices)
44+
45+
if __name__ == "__main__" :
46+
main()

0 commit comments

Comments
 (0)