Comparison of Two Different Initializations of Dijkstra's Algorithm

Everyone is familiar with the dijkstra algorithm . Let’s cut down on nonsense and post the code.


memset(book, 0, sizeof(book)); ///Preprocessing initialization
    for(int i=1; i<=n; i++)
    
        dis[i] = (i == 1 ? 0 : INF);
    for(int i=1;i<=n;i++)
        dis[i]=num[1][i]; ///Initialize the dis array, here is the initial distance from point 1 to the other vertices
    
    book[1]=1; ///Note that this is different from the following, here the source point is marked
    
    for(int i=1; i<n; i++){ ///dijkstra, only n-1 times are needed here
        int x, m = INF;
        for(int y=1; y<=n; y++)
            if(!book[y] && dis[y] < m){ ///Find the shortest distance from the source point
            x = y; ///The subscript of the shortest distance
            m = dis[y]; ///The shortest distance
        }
        book[x] = 1; ///Mark, indicating that the distance from the source point to the x point has been determined
        
        for(int y=1; y<=n ;y++) dis[y] = min(dis[y], dis[x] + num[x][y]);///松弛操作
            
    }
    for(int i=1;i<=n;i++) ///Output the updated shortest distance from the updated source point to the rest of the vertices
    printf("%d ",dis[i]);  
    putchar('\n');

memset(book, 0, sizeof(book)); ///Preprocessing initialization
    for(int i=1; i<=n; i++)
    
        dis[i] = (i == 1 ? 0 : INF);///INF represents a very large value
        /// Note that the source point is not marked here, this is a different
    for(int i=1; i<=n; i++){ ///dijkstra needs n times here
        int x, m = INF;
        for(int y=1; y<=n; y++)
            if(!book[y] && dis[y] < m){ ///Find the shortest distance from the source point
            x = y; ///The subscript of the shortest distance
            m = dis[y]; ///The shortest distance
        }
        book[x] = 1; ///Mark, indicating that the distance from the source point to the x point has been determined
        
        for(int y=1; y<=n ;y++) dis[y] = min(dis[y], dis[x] + num[x][y]);///松弛操作
            
    }
    for(int i=1;i<=n;i++)
    printf("%d ",dis[i]);
    putchar('\n');
 
 


The first code initializes the initial distance from the source point to the rest of the vertices , and marks the source point at the beginning . In the second article , the initial distance from the source point to the other vertices that is not initialized, only initializes each distance to INF, and initializes the distance from the source point to the source point to 0, and does not mark it at the beginning .

For the second code, just after entering, the minimum value m found must be the source point, because the rest of the points are INF, and immediately after the relaxation, the final value of the dis array is the same as

第一篇代码初始时赋的值时一样的。还有第一篇因为刚开始初始化了源点到其余各个顶点的距离,所以只需n-1次松弛就ok了,而第二篇就得需要n次松弛。这就是他们之间的不同,挑篇喜欢的用就行了。


Guess you like

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