In the last articles, we talk about the basic concept about graph. Now we are going to talk about the shortest path.
Let's say we start from A and we aim to go to E.
In order to find the , we can first find and .
Afterwards, we then compare and .
The smallest one will be the shortest path to E. Using the same way, we can find and to get . Below is the pseudocode for shortest path.
Bellman Ford
In fact, the algorithm we used here is the same in the intuitive part. However, the difference is that it uses the flag to check whether the path is updated or not and break the loop until there are no updating.
Dijkstra
In fact, we can make progress in Bellman Ford algorithm.
For example, will be decided when we find the weight from A to B. However, in Bellman Ford algorithm, we will explore the path from A to B many times.
In normal event, if we start from A, we can decide the shortest path from A to its adjacent nodes. Afterwards, we can decide other shortest paths as well. However, we have to ensure that there are no negative weights in graph. Otherwise, the weights can be updated again and again.
Here, we have to spend time to find all the nodes and edges. In fact, we can use heap to find the min edges in . Below, we use priority queue to find the shortest path in .
If the graph has negative loop, we will fail to find the shortest path in finite time.
We couldn't find the shortest path in this graph, because A, B and C form a negative loop . Therefore, we need a way to detect the negative loop.
To determine the shortest path, we only have to update the distance (|V| - 1)th times. Therefore, we can detect that if |V|th times is still updating, then there exist at least a negative loop in the graph.
In this article, we talk about how can we find the shortest path. This is different from going through all the vertexs in the graph which we talked about last time. Also, we learned how to find the shortest path with two different algorithm and also learned how to detect negative loop in a graph. Next time, we will talk about the spanning tree.