Shortest Path#
Before we see how to find the shortest path from vertex
If the graph is unweighted the length of a path is the number of edges it takes to get from
Single source shortest path (SSSP) are all the shortest paths from vertex
For unweighted graphs#
In an unweighted graph we can just use a BFS as this starts with all vertices with distance 1 then 2 etc.
void BFS(Vertex s) {
Queue<Vertex<K>> R = new LinkedList<Vertex<K>>();
s.dist = 0;
R.add(s);
while(!R.isempty()) {
Vertex v = R.remove();
for(Vertex w : v.adjList) {
if (w.dist == Integer.MAX_VALUE) {
w.dist = v.dist + 1;
R.add(w);
}
}
}
}
For weighted graphs#
For a weighted graph this is slightly trickier as the shortest path isn't necessarily the path with the least edges.
Dijkstra's algorithm#
- Assign all the vertices the attributes "finished", "Distance and „Via/Predecessor“. Initialize the distance of the root vertex as 0 and all others as
. - While there are unvisited nodes. So finished=false and distance
.- Choose the vertex
with the smallest distance. - Set
- For all vertices
that have and edge between and- Set int d = v.dist + edge weight between
and . - if(d < w.dist) w.dist = d; w.via = v;
- Set int d = v.dist + edge weight between
- Choose the vertex
The time complexity of this algorithm is as followed. For 1 While loop step 1 takes
For n While loops this the becomes
Improvments#
We could save the vertices that are not finished in a Set so we don't have to look through the entire table. This however doesn't have an effect on the time complexity.
We could save the vertices that are not finished in a Min-Heap. Init=