BFS and shortest path calculation

In the last article we talked about the breadth-first search algorithm. We mentioned that the BFS algorithm has a node search feature similar to Layer-by-Layer. In this article, we continue to talk about the relationship between BFS and the shortest path calculation.

The process of BFS was described in the previous blog, so we won't go into details. Today we will talk about how to calculate the shortest path based on BFS. Still use the diagram in the previous article.

Here we assume that the length of each edge is 1. Of course, if the length of each edge is different, the situation is similar, but it is slightly changed when processing, that is, only the shortest path can be updated.

Initially, we assume that the path length of point s is P=0

Starting from point s, BFS can search for a and b. Since the path of s is 0, the path length of a and b is increased by 1 on the basis of s.

Then search down from the layers of a and b to c and d, so the paths of c and d add 1 to the basis of a and b.

Finally, e is searched, and 1 is added on the basis of c and d.

Some students want to ask, the shortest path seems to have Dij Tesla algorithm, etc., why use BFS here. Note that BFS calculates the shortest distance between the initial point s and all other points here, and we will talk about the Dij Tesla algorithm later. At that time, we will compare the similarities and differences between the two algorithms.

In the introduction to the algorithm, it is mentioned that BFS can only calculate the case where the length of each edge is fixed to 1, and the Dij Tesla algorithm can calculate the case where the length of each edge is different. To be honest, I think BFS can also calculate the case where the length of each edge is different, but it only calculates the minimum time. For example, when updating the length of point e in the above figure, when we go from c to e, update the path length of e. Then when we go from d to e, compare the length of d to e with the existing length of point e at this time. If d to e is shorter, update the path of e. I feel that it can be calculated as well. Of course, if this is the case, it is equivalent to taking every possible route to e, which is a violent solution. In BFS, if point e is marked as explored after c to e, then there will be no possibility of d to e .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324075568&siteId=291194637