MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / floyd_warshall

Function floyd_warshall

graphs/graphs_floyd_warshall.py:19–56  ·  view source on GitHub ↗

:param graph: 2D array calculated from weight[edge[i, j]] :type graph: List[List[float]] :param v: number of vertices :type v: int :return: shortest distance between all vertex pairs distance[u][v] will contain the shortest distance from vertex u to v. 1. For all edges

(graph, v)

Source from the content-addressed store, hash-verified

17
18
19def floyd_warshall(graph, v):
20 """
21 :param graph: 2D array calculated from weight[edge[i, j]]
22 :type graph: List[List[float]]
23 :param v: number of vertices
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 """
35
36 dist = [[float("inf") for _ in range(v)] for _ in range(v)]
37
38 for i in range(v):
39 for j in range(v):
40 dist[i][j] = graph[i][j]
41
42 # check vertex k against all other vertices (i, j)
43 for k in range(v):
44 # looping through rows of graph array
45 for i in range(v):
46 # looping through columns of graph array
47 for j in range(v):
48 if (
49 dist[i][k] != float("inf")
50 and dist[k][j] != float("inf")
51 and dist[i][k] + dist[k][j] < dist[i][j]
52 ):
53 dist[i][j] = dist[i][k] + dist[k][j]
54
55 _print_dist(dist, v)
56 return dist, v
57
58
59if __name__ == "__main__":

Callers 1

Calls 1

_print_distFunction · 0.85

Tested by

no test coverage detected