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

Method dijkstra

graphs/dijkstra_alternate.py:49–82  ·  view source on GitHub ↗

Function that implements Dijkstra's single source shortest path algorithm for a graph represented using adjacency matrix representation. >>> Graph(4).dijkstra(1) # doctest: +NORMALIZE_WHITESPACE Vertex Distance from Source 0 10000000 1 0

(self, source: int)

Source from the content-addressed store, hash-verified

47 return min_index
48
49 def dijkstra(self, source: int) -> None:
50 """
51 Function that implements Dijkstra's single source shortest path algorithm for a
52 graph represented using adjacency matrix representation.
53
54 >>> Graph(4).dijkstra(1) # doctest: +NORMALIZE_WHITESPACE
55 Vertex Distance from Source
56 0 10000000
57 1 0
58 2 10000000
59 3 10000000
60 """
61
62 distances = [int(1e7)] * self.vertices # distances from the source
63 distances[source] = 0
64 visited = [False] * self.vertices
65
66 for _ in range(self.vertices):
67 u = self.minimum_distance(distances, visited)
68 visited[u] = True
69
70 # Update dist value of the adjacent vertices
71 # of the picked vertex only if the current
72 # distance is greater than new distance and
73 # the vertex in not in the shortest path tree
74 for v in range(self.vertices):
75 if (
76 self.graph[u][v] > 0
77 and visited[v] is False
78 and distances[v] > distances[u] + self.graph[u][v]
79 ):
80 distances[v] = distances[u] + self.graph[u][v]
81
82 self.print_solution(distances)
83
84
85if __name__ == "__main__":

Callers 1

Calls 2

minimum_distanceMethod · 0.95
print_solutionMethod · 0.95

Tested by

no test coverage detected