@@ -57,6 +57,7 @@ $ pip install py-algorithms
57
57
- Breadth-First-Search (BFS)
58
58
- Topologial sort
59
59
- Floyd–Warshall algorithm
60
+ - Dijkstra's algorithm
60
61
61
62
---
62
63
@@ -530,6 +531,52 @@ topological_sort_f1(dag) #=> [#<Vertex(C)>, #<Vertex(B)>, #<Vertex(D)>, #<Vertex
530
531
531
532
```
532
533
534
+ ### Dijkstra's algorithm
535
+
536
+ ![ ] ( https://upload.wikimedia.org/wikipedia/commons/5/57/Dijkstra_Animation.gif )
537
+
538
+ ``` python
539
+ from py_algorithms.graph import new_undirected_graph
540
+ from py_algorithms.graph new_dijkstra_shortest_path
541
+ from py_algorithms.graph reconstruct_dijkstra_path_tree
542
+
543
+ graph = new_undirected_graph()
544
+ a = graph.insert_vertex(' A' )
545
+ b = graph.insert_vertex(' B' )
546
+ c = graph.insert_vertex(' C' )
547
+ d = graph.insert_vertex(' D' )
548
+ e = graph.insert_vertex(' E' )
549
+
550
+ graph.insert_edge(a, e, 10 )
551
+ graph.insert_edge(b, d, 2 )
552
+ graph.insert_edge(c, d, 3 )
553
+ graph.insert_edge(d, e, 12 )
554
+
555
+ # Start from vertex "c" and grow the cluster.
556
+ paths = new_dijkstra_shortest_path(graph, c)
557
+
558
+ assert paths[c] == 0
559
+ assert paths[d] == 3
560
+ assert paths[b] == 5
561
+ assert paths[e] == 15
562
+ assert paths[a] == 25
563
+
564
+ # Reconstructing particulat shortest path
565
+ path_tree = reconstruct_dijkstra_path_tree(graph, c, paths)
566
+
567
+ root = a
568
+ stack = []
569
+ while root != c:
570
+ stack.append(root)
571
+ root = path_tree[root].opposite(root)
572
+ stack.append(root)
573
+
574
+
575
+ # The shortest path to reach vertex "a":
576
+ assert stack == [a, e, d, c]
577
+
578
+ ```
579
+
533
580
---
534
581
535
582
### String Algorithms
0 commit comments