shortest path dijkstra&&

Dijkstra's algorithm

Dijkstra's algorithm uses a greedy strategy.

Declare an array d to hold the shortest distances from the source to each vertex and a collection to hold the vertices for which the shortest path has been found: T.

Initially, the path weight of the origin s is assigned 0 (d[s] = 0). If there is a directly reachable edge (s,m) for vertex s, then set d[m] to the distance from s to m, and set the path length of all other (s unreachable) vertices to infinity. Initially, the set T has only vertex s. 

Then, select the minimum value from the dis array, then the value is the shortest path from the source point s to the vertex corresponding to this value, and add this point to T, OK, then a vertex is completed, 
and then we need to look at the new Whether the added vertices can reach other vertices and see if the path length to reach other points through this vertex is shorter than the source point directly, if so, then replace the value of these vertices in dis. 
Then, find the minimum value from dis, and repeat the above actions until T contains all the vertices of the graph.

 

 

dijkstra template:

#include<stdio.h>
#include<string.h>
#define INFINITY 1000
int d[100];
int final[100];
int g[100][100];
int n;
void dijkstra(int s)
{
    int min, w, v, i, j;
    memset(final, 0, sizeof(final));
    for(v = 1; v <= n; v++)
        d[v] = g[s][v];
    final[s] = 1;
    d[s] = 0 ;
     for (i = 2 ; i <= n; i++) // The shortest of each point in the line corresponding to this point is found 
    {
        min = INFINITY;
        v = - 1 ;
         for (w = 1 ; w <= n; w++) // Among all the unmarked points, select the point with the smallest D value 
        {
             if (!final[w] && d[w] < min)
            {
                v = w;
                min = d [w];
            }
        }

        if (v != - 1 ) // If v=-1, it means that the point you are looking for does not have a path with any other point 
        {
            final[v] = 1 ;

            for (w = 1 ; w <= n; w++) // find the new point connected to it after finding the most segment path 
                if ((!final[w]) && (g[v][w] < INFINITY))
                {
                    if(d[w] > min + g[v][w])
                        d [w] = min + g [v] [w];
                }
        }
    }
}
intmain ()
{
    int i, j;
    scanf("%d", &n);
    for(i = 1; i <= n; i++)
        for(j = 1; j <= n; j++)
            scanf("%d", &g[i][j]);
    dijkstra(1);
    for(i = 1; i <= n; i++)
        printf("%d ", d[i]);
    return 0;
}

 

 

 

 

 

 

Reference blog: The shortest path problem---Detailed explanation of Dijkstra's algorithm

Guess you like

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