@@ -14,36 +14,57 @@ def _print_dist(dist, v):
14
14
else :
15
15
print ("INF" , end = "\t " )
16
16
print ()
17
-
18
-
19
17
def floyd_warshall (graph , v ):
20
18
"""
21
- :param graph: 2D array calculated from weight[edge[i, j]]
19
+ Computes the shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles).
20
+
21
+ :param graph: 2D list where each element represents the weight from i to j.
22
22
:type graph: List[List[float]]
23
- :param v: number of vertices
23
+ :param v: Number of vertices in the graph.
24
24
:type v: int
25
- :return: shortest distance between all vertex pairs
26
- distance[u][v] will contain the shortest distance from vertex u to v.
27
-
28
- 1. For all edges from v to n, distance[i][j] = weight(edge(i, j)).
29
- 3. The algorithm then performs distance[i][j] = min(distance[i][j], distance[i][k] +
30
- distance[k][j]) for each possible pair i, j of vertices.
31
- 4. The above is repeated for each vertex k in the graph.
32
- 5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is
33
- updated to the next vertex[i][k].
34
- """
25
+ :return: A tuple containing the distances matrix and number of vertices.
26
+
27
+ Example:
28
+ >>> v = 3
29
+ >>> inf = float('inf')
30
+ >>> graph = [
31
+ ... [0, 1, inf],
32
+ ... [inf, 0, 1],
33
+ ... [1, inf, 0]
34
+ ... ]
35
+ >>> dist, _ = floyd_warshall(graph, v) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
36
+ <BLANKLINE>
37
+ The shortest path matrix using Floyd Warshall algorithm
38
+ <BLANKLINE>
39
+ 0 1 2
40
+ 2 0 1
41
+ 1 2 0
42
+ >>> [int(x) if x != inf else 'INF' for row in dist for x in row]
43
+ [0, 1, 2, 2, 0, 1, 1, 2, 0]
44
+
45
+ Handling a graph with no edges:
46
+ >>> v = 3
47
+ >>> graph = [[inf]*3 for _ in range(3)]
48
+ >>> for i in range(3): graph[i][i] = 0
49
+ >>> dist, _ = floyd_warshall(graph, v) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
50
+ <BLANKLINE>
51
+ The shortest path matrix using Floyd Warshall algorithm
52
+ <BLANKLINE>
53
+ 0 INF INF
54
+ INF 0 INF
55
+ INF INF 0
56
+ >>> [int(x) if x != inf else 'INF' for row in dist for x in row]
57
+ [0, 'INF', 'INF', 'INF', 0, 'INF', 'INF', 'INF', 0]
35
58
59
+ """
36
60
dist = [[float ("inf" ) for _ in range (v )] for _ in range (v )]
37
61
38
62
for i in range (v ):
39
63
for j in range (v ):
40
64
dist [i ][j ] = graph [i ][j ]
41
65
42
- # check vertex k against all other vertices (i, j)
43
66
for k in range (v ):
44
- # looping through rows of graph array
45
67
for i in range (v ):
46
- # looping through columns of graph array
47
68
for j in range (v ):
48
69
if (
49
70
dist [i ][k ] != float ("inf" )
@@ -57,6 +78,8 @@ def floyd_warshall(graph, v):
57
78
58
79
59
80
if __name__ == "__main__" :
81
+ import doctest
82
+ doctest .testmod ()
60
83
v = int (input ("Enter number of vertices: " ))
61
84
e = int (input ("Enter number of edges: " ))
62
85
0 commit comments