Dijkstra
Dijkstra's algorithm is a popular algorithm in computer science used to find the shortest path between nodes in a graph, particularly in weighted graphs where each edge has a numerical weight.
It was conceived by Dutch computer scientist Edsger W. Dijkstra in 1956.
Here's a basic explanation of how Dijkstra's algorithm works:
Initialization: Assign a tentative distance value to every node. Set the initial node's distance to 0 and all others to infinity. Keep track of a priority queue (usually implemented with a min-heap) of all nodes, prioritized by their tentative distance values.
Visit Nodes: Visit each node in the graph starting from the initial node. For the current node, consider all of its neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one.
Update Priority Queue: After updating the tentative distances of neighboring nodes, reorder the priority queue based on the new tentative distances.
Repeat: Repeat steps 2 and 3 until all nodes have been visited.
Result: Once all nodes have been visited, the algorithm will have found the shortest path from the initial node to all other nodes.
pseudocode:
In this example, graph
represents an adjacency list where each key represents a vertex, and the value associated with each key is another object representing the neighbors of that vertex and the weight of the edge to each neighbor.
The function dijkstra
calculates the shortest path from the start
vertex to every other vertex in the graph and returns an object with the shortest distances.
The PriorityQueue
is used to efficiently select the next vertex to visit based on its tentative distance.
Last updated