Single-source shortest path dijkstra Algorithm Implementation
This article records the implementation of the dijkstra algorithm. The graph is represented by an adjacent matrix. For example, if the graph is an undirected graph and connected to a directed graph, the practice of an unconnected graph is similar.
Algorithm Description:
First, determine the source of "single source". Assume It is 0th vertices.
Maintain three Arrays: dist [], color [], path [], and set their subscript to 0... I... N-1:
Dist [] indicates the shortest distance from the source point to vertex I. during initialization, if there is a path from the source point to vertex I, it is initialized to the path weight; otherwise, it is initialized to INT_MAX;
The color [] array actually represents two sets, that is, the set with the color [I] value of 1 represents the set of vertices that have determined the shortest path, the Value of color [I] is 0, indicating the set of vertices with no minimum path determined. Initialize to set the color of the Source Vertex to 1, and set the remaining vertex to 0;
Path [] indicates the path from the array to vertex I. If path [I] = 3, path [3] = 2, paht [2] = 0, the shortest path is 0-> 2-> 3-> I, and the order given by the array is backward.
Select the smallest dist value from the dist [] array in sequence. If the coordinate of the vertex is index, the dist value is the final point of the shortest distance, update the color value of this vertex to 1. The following operation is the focus of the dijkstra algorithm, and there is only one key operation, namely:If the distance from the source vertex to the index is less than the distance from the index to these vertices, update the dist value.And update the path value.
Repeat 3rd operations until the set with the color value 0 is null.
The C language implementation code is given below, and the methods are commented out. I will not describe it here. If there are deficiencies, please put forward (the default figure is as follows ):
# Include
# Include
# Include
Int n; int source = 0; // calculate the shortest path from 0th nodes to other nodes: int * dist; int * path; int * color; // if the color is 1, the shortest path has been found. If the color is-1, the shortest path has not been found. // obtain the default graph, that is, as shown in. Use the adjacent matrix to represent int ** get_graph () {int ** matrix; int I, j; int start, end, weight; printf (input vertex num :); scanf (% d, & n ); matrix = (int **) malloc (sizeof (int *) * n); for (I = 0; I
The running result is as follows: