MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / show_path

Method show_path

graphs/dijkstra_algorithm.py:394–436  ·  view source on GitHub ↗

Shows the shortest path from src to dest. WARNING: Use it *after* calling dijkstra. Examples: >>> graph_test = Graph(4) >>> graph_test.add_edge(0, 1, 1) >>> graph_test.add_edge(1, 2, 2) >>> graph_test.add_edge(2, 3, 3) >>> graph_test.

(self, src, dest)

Source from the content-addressed store, hash-verified

392 print(f"Node {u} has distance: {self.dist[u]}")
393
394 def show_path(self, src, dest):
395 """
396 Shows the shortest path from src to dest.
397 WARNING: Use it *after* calling dijkstra.
398
399 Examples:
400 >>> graph_test = Graph(4)
401 >>> graph_test.add_edge(0, 1, 1)
402 >>> graph_test.add_edge(1, 2, 2)
403 >>> graph_test.add_edge(2, 3, 3)
404 >>> graph_test.dijkstra(0)
405 Distance from node: 0
406 Node 0 has distance: 0
407 Node 1 has distance: 1
408 Node 2 has distance: 3
409 Node 3 has distance: 6
410 >>> graph_test.show_path(0, 3) # doctest: +NORMALIZE_WHITESPACE
411 ----Path to reach 3 from 0----
412 0 -> 1 -> 2 -> 3
413 Total cost of path: 6
414 """
415 path = []
416 cost = 0
417 temp = dest
418 # Backtracking from dest to src
419 while self.par[temp] != -1:
420 path.append(temp)
421 if temp != src:
422 for v, w in self.adjList[temp]:
423 if v == self.par[temp]:
424 cost += w
425 break
426 temp = self.par[temp]
427 path.append(src)
428 path.reverse()
429
430 print(f"----Path to reach {dest} from {src}----")
431 for u in path:
432 print(f"{u}", end=" ")
433 if u != dest:
434 print("-> ", end="")
435
436 print("\nTotal cost of path: ", cost)
437
438
439if __name__ == "__main__":

Callers 1

Calls 2

reverseMethod · 0.80
appendMethod · 0.45

Tested by

no test coverage detected