Skip to content

Commit 00575aa

Browse files
committed
Add Floyd-Warshall Algorithm
1 parent 176c330 commit 00575aa

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Diff for: data_structures/Graph/FloydWarshall.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
def printDist(dist, V):
3+
print("\nThe shortest path matrix using Floyd Warshall algorithm\n")
4+
for i in range(V):
5+
for j in range(V):
6+
if dist[i][j] != float('inf') :
7+
print(int(dist[i][j]),end = "\t")
8+
else:
9+
print("INF",end="\t")
10+
print();
11+
12+
13+
14+
def FloydWarshall(graph, V):
15+
dist=[[float('inf') for i in range(V)] for j in range(V)]
16+
17+
for i in range(V):
18+
for j in range(V):
19+
dist[i][j] = graph[i][j]
20+
21+
for k in range(V):
22+
for i in range(V):
23+
for j in range(V):
24+
if dist[i][k]!=float('inf') and dist[k][j]!=float('inf') and dist[i][k]+dist[k][j] < dist[i][j]:
25+
dist[i][j] = dist[i][k] + dist[k][j]
26+
27+
printDist(dist, V)
28+
29+
30+
31+
#MAIN
32+
V = int(input("Enter number of vertices: "));
33+
E = int(input("Enter number of edges: "));
34+
35+
graph = [[float('inf') for i in range(V)] for j in range(V)]
36+
37+
for i in range(V):
38+
graph[i][i] = 0.0;
39+
40+
for i in range(E):
41+
print("\nEdge ",i+1)
42+
src = int(input("Enter source:"))
43+
dst = int(input("Enter destination:"))
44+
weight = float(input("Enter weight:"))
45+
graph[src][dst] = weight;
46+
47+
FloydWarshall(graph, V)

0 commit comments

Comments
 (0)