Dijkstra's shortest path algorithm
This algorithm uses a greedy approach in that we find the next best solution in hope that it will lead to a generalized optimal solution. Vertices are denoted by u and v. In our case in the above grid we place the weights inside the vertex denoting the weight to get to it.
Weighted edges that connect two nodes (u, v) are denoted as w(u, v).
dist is an array of distances from source s to every node in the graph. s is initialized as 0 and for all other nodes we initialize them as ∞. dist(v) = ∞
We use a queue (Q) data structure to store all nodes in the graph and at the end of the algorithm the queue will be empty.
S - an empty set to indicate which nodes the algorithm has visited. At the end of the algorithm, S will contain all nodes of the graph.
Algorithm
1. While Q is not empty, we pop the node v that is not in S from Q with the smallest distance dist(v). In the first iteration the source node is chosen because we initialized it with 0. In the following iterations nodes with the smallest weight values will be chosen.
2. We add node v to S, to indicate that v has been visited.
3. We update dist values of adjacent nodes of the current node v by doing the following: for each new adjacent node u,
1. if dist(v) + weight(u,v) < dist(u), that means there is a minimal distance found for u.
1. update dist(u) to the new minimal distance value.
2. Otherwise don't update dist(u).
4. In the end the algorithm has visited all nodes in the graph and dist array will contain the shortest path(smallest distance) from source s to destination.
Computational complexity
This algorithm takes O(V + E log V) in the all cases where V is the number of vertices and E is the number of edges.It has a O(V) space complexity. It stores V, the number of vertices.
Applications
- Open Shortest Path First (OSPF) algorithm for packet routing.
- telephone networking.
- social network algorithms.
- maps and gps navigation software.
- Drone/robotic path routing.
- Designating a file server.