Single Source Shortest Path
By single source shortest path, we mean that we need to find the shortest path from a specific source vertex to all other vertices.
We can achieve the solution in two ways.
Djikstra's Algorithm
Algorithm
-
Initialize an empty \(n\ \text x\ n\) matrix and in the first column set the distance of the source vertex to be \(0\) and rest other vertices to \(\infin\)
-
Find the vertex \(v\) with the least distance \(d.\) Mark \(v\) as visited.
-
Check the neighbours of \(v\) and check whether they are unvisited. If the neighbout is not visited, then check for \(d[v]+W<d[n].\) If it is the case, then assign this value to \(d[n].\)
-
Repeat steps (3) and (4) for all the unvisited vertices.
Implementation
Using a NumPy Array
Using an Adjacency List
Time Complexity
The time complexity for Djikstra's Algorithm in either of the two cases is \(O(n^2).\)
You can minimise this using Heaps as discussed in further articles.
Danger
Djikstra's Algorithm does not allow the presence of negative edge weights in the graph.
Bellman-Ford Algorithm
Bellman Ford Algorithm is an algorithm to find Single Source Shortest Paths similar to the Djikstra's Algorithm except the fact that it allows the use of negative edge weights but not a negative cycle.
Algorithm
- Initialise a dictionary \(D\) that stores the distance and \(D(v) = \begin{bmatrix}0 \text{, If v is source vertex}\\ \infin \text{, otherwise}\end{bmatrix}\)
- Pick a vertex \(j\) that has an edge \((j,k)\) and set \(D(k) = min(D(k), D(j)+\text{weight}(j, k))\)
- Repeat the step \(2\) for \(n-1\) times.
Implementation
Using Numpy Array
Using Adjancency List
Time Complexity
- Using the numpy method the time complexity is \(O(n^3)\)
- Shifting to the Adjacency List the time complexity becomes \(O(mn),\) where \(m\) is the number of edges and \(n\) is the number of vertices.