1
+ # Python Program for Floyd Warshall Algorithm
2
+
3
+ # Number of vertices in the graph
4
+ V = 4
5
+
6
+ # Define infinity as the large enough value. This value will be
7
+ # used for vertices not connected to each other
8
+ INF = 99999
9
+
10
+ # Solves all pair shortest path via Floyd Warshall Algorithm
11
+ def floydWarshall (graph ):
12
+
13
+ """ dist[][] will be the output matrix that will finally
14
+ have the shortest distances between every pair of vertices """
15
+ """ initializing the solution matrix same as input graph matrix
16
+ OR we can say that the initial values of shortest distances
17
+ are based on shortest paths considering no
18
+ intermediate vertices """
19
+ dist = map (lambda i : map (lambda j : j , i ) , graph )
20
+
21
+ """ Add all vertices one by one to the set of intermediate
22
+ vertices.
23
+ ---> Before start of an iteration, we have shortest distances
24
+ between all pairs of vertices such that the shortest
25
+ distances consider only the vertices in the set
26
+ {0, 1, 2, .. k-1} as intermediate vertices.
27
+ ----> After the end of a iteration, vertex no. k is
28
+ added to the set of intermediate vertices and the
29
+ set becomes {0, 1, 2, .. k}
30
+ """
31
+ for k in range (V ):
32
+
33
+ # pick all vertices as source one by one
34
+ for i in range (V ):
35
+
36
+ # Pick all vertices as destination for the
37
+ # above picked source
38
+ for j in range (V ):
39
+
40
+ # If vertex k is on the shortest path from
41
+ # i to j, then update the value of dist[i][j]
42
+ dist [i ][j ] = min (dist [i ][j ] ,
43
+ dist [i ][k ]+ dist [k ][j ]
44
+ )
45
+ printSolution (dist )
46
+
47
+
48
+ # A utility function to print the solution
49
+ def printSolution (dist ):
50
+ print "Following matrix shows the shortest distances\
51
+ between every pair of vertices "
52
+ for i in range (V ):
53
+ for j in range (V ):
54
+ if (dist [i ][j ] == INF ):
55
+ print "%7s" % ("INF" ),
56
+ else :
57
+ print "%7d\t " % (dist [i ][j ]),
58
+ if j == V - 1 :
59
+ print ""
60
+
61
+
62
+
63
+ # Driver program to test the above program
64
+ # Let us create the following weighted graph
65
+ """
66
+ 10
67
+ (0)------->(3)
68
+ | /|\
69
+ 5 | |
70
+ | | 1
71
+ \|/ |
72
+ (1)------->(2)
73
+ 3 """
74
+ graph = [[0 ,5 ,INF ,10 ],
75
+ [INF ,0 ,3 ,INF ],
76
+ [INF , INF , 0 , 1 ],
77
+ [INF , INF , INF , 0 ]
78
+ ]
79
+ # Print the solution
80
+ floydWarshall (graph );
0 commit comments