Graph Theory (3) (1) Shortest Path Algorithm 4.SPFA Algorithm (1)

What I'm talking about today is the last algorithm commonly used to solve the shortest path problem. This algorithm is also to find the shortest path from a single source point to other nodes in a connected graph. Its function is roughly the same as the Bellman-Ford algorithm, and it can find edges with negative weights , but no negative loops can appear . But the time complexity of SPFA algorithm is O(kE), k is a constant, the average is 2, and E is the number of edges. We can see that the time complexity of the SPFA algorithm is much lower than the Bellman-Ford algorithm, so this algorithm is often chosen instead of the Bellman algorithm (although its complexity is not strictly mathematically proven).

Simply put, SPFA is an implementation that combines the Bellman-Ford algorithm with a queue, thereby reducing a lot of redundant calculations.

The text description is as follows: Initially, the starting point is added to the queue. One element is taken out of the queue at a time, and all adjacent points are modified. If an adjacent point is modified successfully, it will be added to the queue. The algorithm ends when the queue is empty.

Pseudo code description:

dis[i] records the shortest path from the starting point s to i, m[i][j] records the length of the edge connecting i and j, and pre[v] records the precursor node.

t[1..n] is the queue, the head pointer is head, and the tail pointer is tail.

The boolean array e[1..n] records whether a point is currently in the queue.

Initialization: dis[s]=0,dis[v]=∞,memset(e,false,sizeof(e));

Start queue t[1]=s;head=0;tail=1;e[s]=true;

do

{

1. Move the head pointer down and take out point u.

2.e[u]=false; has been taken out of the queue.

3.for all points v connected to u

 if(dis[v]>dis[u]+m[u][v]){

    dis[v]=dis[u]+m[u][v];

    for [v] = u;

    if(!e[v])// v is not in the queue, v is in the queue

     {

       The tail pointer moves down, and v joins the queue;

       e [v] = true [

     }

  }

}while(head<tail);

important point:

1. Because the size of the queue is unknown and easy to exceed expectations, the idea of ​​​​a circular queue is adopted , that is, the queue length does not need to be very large.

2. The algorithm feels similar to Guangsou, but unlike Guangsou, the elements that are dequeued by Guangsou will not be listed, and the elements in the queue will be adjusted as needed.

The specific code will be used in the next question, so I won't write it here.

3. In the step of enumerating all points, the premise is to use the graph stored in the adjacency matrix before enumerating, otherwise the time complexity will not be improved.

Guess you like

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