Introduction
Dijkstra is a typical single-source shortest path calculation algorithm.
Calculate the shortest path from one node to all other nodes. The main feature is to expand horizontally at the center of the starting point until the end point is reached. Dijkstra algorithm is the most representative short circuit.
Path Algorithms are described in detail in many professional courses, such as data structures, graph theory, and operational research. Generally, Dijkstra can be expressed in two ways: permanent and temporary.
One way is to use open and close tables. both permanent and temporary labels are used here. Note that this algorithm requires that no negative weight edge exists in the graph.
Algorithm Description
(Here we describe the Dijkstra algorithm from node 1 to each point, where wa-> B indicates the Edge Weight of A-> B, d (I) that is, the shortest path value)
1. set the set S to {2, 3 ,... n}, array D (1) = 0, d (I) = W1-> I (1, an edge exists between I) or + infinity (1. there is no edge between I)
2. in S, make D (j) = min {d (I), I belong to s}, and S = s-{J}. If s is an empty set, the algorithm ends, otherwise, go to 3.
3. for all I belong to S, if edge J-> I exists, set d (I) = min {d (I), D (j) + WJ-> I }, go 2
Complexity Analysis
The time complexity of Dijkstra algorithm is O (n ^ 2)
The space complexity depends on the storage method, and the adjacent matrix is O (n ^ 2)
Algorithm Implementation
Input/Output Format
Input Format:
Row 1st: N represents n nodes.
Row 2-N + 1: N numbers in each row, representing the graph's Adjacent matrix, with no edge connected to-1
Output Format:
Row 1st: n-1 number, which is the shortest path from node 1 to node 2-N.
C ++
# Include <fstream>
# Include <cstring>
Using namespace STD;
Const int maxnum = 1000000; // maximum Edge Weight
Int N; // number of nodes
Int Dist [501]; // the shortest path to node 1
Bool State [501]; // indicates the status of a node that has been searched.
Int data [501] [501]; // adjacent matrix
// Find the node with the smallest weight
Int findmin ()
{
Int minnode = 0, min = maxnum;
For (INT I = 1; I <= N; I ++)
If (Dist [I] <min )&&(! State [I])
{
Min = DIST [I];
Minnode = I;
}
Return minnode;
}
Int main ()
{
Ifstream in ("Dijkstra. In ");
Ofstream out ("Dijkstra. Out ");
Memset (State, 0, sizeof (State ));
In> N;
For (INT p = 1; P <= N; P ++)
For (INT q = 1; q <= N; q ++)
{
In> data [p] [Q];
If (data [p] [Q] = 0) data [p] [Q] = maxnum;
}
// Initialization
For (INT I = 1; I <= N; I ++)
Dist [I] = data [1] [I];
State [1] = true;
Int done = 1;
While (done <n)
{
Int node = findmin ();
If (node! = 0)
{
Done ++; // Add 1 to the number of points found
State [node] = true; // indicates that the shortest path from node 1 to node is found.
For (INT I = 1; I <= N; I ++) // update the PATH value of a vertex not found.
If (Dist [I]> Dist [node] + data [node] [I]) & (! State [I])
Dist [I] = DIST [node] + data [node] [I];
}
Else break;
}
For (INT p = 1; P <= N; P ++)
{
If (Dist [p] = maxnum)
Out <-1;
Else
Out <Dist [p];
If (P = N)
Out <Endl;
Else
Out <"";
}
In. Close ();
Out. Close ();
Return 0;
}
Pascal
Program Dijkstra;
VaR
State: array [1 .. 100] of Boolean;
Data: array [1 .. 100, 1 .. 100] of longint;
N, I, J, K, Min, node: longint;
Begin
Assign (input, 'dijkstra. in ');
Assign (output, 'dijkstra. out ');
Reset (input );
Rewrite (output );
Fillchar (data, sizeof (data), 0 );
Fillchar (State, sizeof (state), 0 );
Readln (N );
For I: = 1 to n do
For J: = 1 to n do
Begin
Read (data [I, j]);
If data [I, j] = 0 then data [I, j]: = maxint;
End;
State [1]: = true;
For K: = 2 to n do
Begin
Min: = maxint;
{Node is the smallest point in the search weight}
Node: = 1;
For I: = 2 to n do
If (data [1, I] <min) and (State [I] = false) then
Begin
Min: = data [1, I];
Node: = I;
End;
{Update the weights of other points}
State [node]: = true;
For J: = 1 to n do
If (data [1, node] + data [node, J] <data [1, J]) and (State [J] = false) then
Data [1, J]: = data [1, node] + data [node, J];
End;
For I: = 1 to n-1 do
If data [1, I] <> maxint then
Write (data [1, I], '')
Else
Write (-1 ,'');
Writeln (data [1, N]);
Close (input );
Close (output );
End.
Test example
Sample Input
7
00 20 50 30 00 00 00
20 00 25 00 00 70 00
50 25 00 40 25 50 00
30 00 40 00 55 00 00
00 00 25 55 00 10 00
00 70 50 00 10 00 00
00 00 00 00 00 00
Sample output
-1 20 45 30 70 80-1
Rough Process
Create two tables, open and close.
The Open Table stores all generated nodes that have not been investigated. The closed table records the accessed nodes.
1. Place the point closest to the start point and not checked in the road network in the Open Group for inspection.
2. Locate the point closest to the start point in the Open table, locate all the subnodes of the point, and place the point in the close table.
3. traverse the child nodes of This vertex. Find the distance between these subnode points and the starting point, and place the subnode in the Open table.
4. Repeat steps 2 and 3. Until the Open table is empty or the target point is found.
/* Dijkstra. c
Copyright (c) 2002,200 6 by ctu_85
All rights reserved.
*/
# Include "stdio. H"
# Include "malloc. H"
# Define maxium 32767
# Define maxver 9/* defines the Max number of vertexs which the programm can handle */
# Define OK 1
Struct point
{
Char vertex [3 ];
Struct link * work;
Struct point * next;
};
Struct Link
{
Char vertex [3 ];
Int value;
Struct link * next;
};
Struct table/* The workbannch of the algorithm */
{
Int cost;
Int known;
Char vertex [3 ];
Char path [3 ];
Struct table * next;
};
Int Dijkstra (struct point *, struct table *);
Int printtable (INT, struct table *);
Int printpath (INT, struct table *, struct table *);
Struct table * createtable (INT, INT );
Struct point * findsmallest (struct table
*, Struct point *);/* Find the vertex which has the smallest value reside
In the table */
Int main ()
{
Int I, j, num, temp, Val;
Char C;
Struct point * poinpre, * poinhead, * poin;
Struct link * linpre, * linhead, * Lin;
Struct table * tabhead;
Poinpre = poinhead = poin = (struct point *) malloc (sizeof (struct point ));
Poin-> next = NULL;
Poin-> Work = NULL;
Restart:
Printf ("Notice: If you wanna to input a vertex, you must use the format of number! /N ");
Printf ("Please input the number of points:/N ");
Scanf ("% d", & num );
If (Num> maxver | num <1 | num % 1! = 0)
{
Printf ("/nNumber of points exception! ");
Goto restart;
}
For (I = 0; I {
Printf ("Please input the points next to point % d, end with 0:/N", I + 1 );
Poin = (struct point *) malloc (sizeof (struct point ));
Poinpre-> next = poin;
Poin-> vertex [0] = 'V ';
Poin-> vertex [1] = '0' + I + 1;
Poin-> vertex [2] = '/0 ';
Linpre = lin = Poin-> work;
Linpre-> next = NULL;
For (j = 0; J {
Printf ("the number of the % d th vertex linked to vertex % d:", J + 1, I + 1 );
Scanf ("% d", & temp );
If (temp = 0)
{
Lin-> next = NULL;
Break;
}
Else
{
Lin = (struct link *) malloc (sizeof (struct link ));
Linpre-> next = Lin;
Lin-> vertex [0] = 'V ';
Lin-> vertex [1] = '0' + temp;
Lin-> vertex [2] = '/0 ';
Printf ("Please input the value betwixt % d th point towards % d th point:", I + 1, temp );
Scanf ("% d", & Val );
Lin-> value = val;
Linpre = linpre-> next;
Lin-> next = NULL;
}
}
Poinpre = poinpre-> next;
Poin-> next = NULL;
}
Printf ("Please enter the vertex where Dijkstra algorithm starts:/N ");
Scanf ("% d", & temp );
Tabhead = createtable (temp, num );
Dijkstra (poinhead, tabhead );
Printtable (temp, tabhead );
Return OK;
}
Struct table * createtable (INT vertex, int total)
{
Struct table * head, * Pre, * P;
Int I;
Head = pre = P = (struct table *) malloc (sizeof (struct table ));
P-> next = NULL;
For (I = 0; I {
P = (struct table *) malloc (sizeof (struct table ));
Pre-> next = P;
If (I + 1 = vertex)
{
P-> vertex [0] = 'V ';
P-> vertex [1] = '0' + I + 1;
P-> vertex [2] = '/0 ';
P-> Cost = 0;
P-> known = 0;
}
Else
{
P-> vertex [0] = 'V ';
P-> vertex [1] = '0' + I + 1;
P-> vertex [2] = '/0 ';
P-> Cost = maxium;
P-> known = 0;
}
P-> next = NULL;
Pre = pre-> next;
}
Return head;
}
Int Dijkstra (struct point * P1, struct table * P2)/* Core of the programm */
{
Int costs;
Char temp;
Struct point * poinhead = p1, * now;
Struct link * Linna;
Struct table * tabhead = P2, * searc, * result;
While (1)
{
Now = findsmallest (tabhead, poinhead );
If (now = NULL)
Break;
Result = P2;
Result = Result-> next;
While (result! = NULL)
{
If (result-> vertex [1] = now-> vertex [1 ])
Break;
Else
Result = Result-> next;
}
Linna = now-> Work-> next;
While (Linna! = NULL)/* update all the vertexs linked to the signed vertex */
{
Temp = Linna-> vertex [1 ];
Searc = tabhead-> next;
While (searc! = NULL)
{
If (searc-> vertex [1] = temp)/* Find the vertex linked to the signed vertex in the table and update */
{
If (result-> Cost + Linna-> value) cost)
{
Searc-> Cost = Result-> Cost + Linna-> value;/* set the new value */
Searc-> path [0] = 'V ';
Searc-> path [1] = now-> vertex [1 ];
Searc-> path [2] = '/0 ';
}
Break;
}
Else
Searc = searc-> next;
}
Linna = Linna-> next;
}
}
Return 1;
}
Struct point * findsmallest (struct table * head, struct point * poinhead)
{
Struct point * result;
Struct table * temp;
Int min = maxium, status = 0;
Head = head-> next;
Poinhead = poinhead-> next;
While (Head! = NULL)
{
If (! Head-> known & head-> Cost {
Min = head-> cost;
Result = poinhead;
Temp = head;
Status = 1;
}
Head = head-> next;
Poinhead = poinhead-> next;
}
If (Status)
{
Temp-> known = 1;
Return result;
}
Else
Return NULL;
}
Int printtable (INT start, struct table * head)
{
Struct table * begin = head;
Head = head-> next;
While (Head! = NULL)
{
If (Head-> vertex [1]-'0 ')! = Start)
Printpath (START, Head, begin );
Head = head-> next;
}
Return OK;
}
Int printpath (INT start, struct table * head, struct table * begin)
{
Struct table * temp = begin-> next, * P, * t;
P = head;
T = begin;
If (P-> vertex [1]-'0 ')! = Start & P! = NULL)
{
While (temp-> vertex [1 ]! = P-> path [1] & temp! = NULL)
Temp = temp-> next;
Printpath (START, temp, t );
Printf ("% s", p-> vertex );
}
Else
If (P! = NULL)
Printf ("/n % s", p-> vertex );
Return OK;
Time Complexity
We can use a large O symbol to express the running time of Dijkstra algorithm as a function of the number of edges m and the number of vertices n.
The simplest way to implement the Dijkstra algorithm is to use a linked list or array to store the Q set of all vertices. Therefore, the calculation of the minimum element in Q is searched (extract-min (q )) you only need to linearly search all the elements in Q. In this case, the algorithm runs at O (n2 ).
For a sparse graph with fewer edges than N2, we can use an adjacent table to implement the Dijkstra algorithm more effectively. At the same time, a binary heap or Fibonacci heap needs to be used as a priority queue to find the smallest vertex (extract-min ). When a binary heap is used, the algorithm takes O (m + n) log n). The Fibonacci heap can slightly improve the performance, set the algorithm running time to O (m + n log n ). Related Questions and Algorithms
The functions can be extended by making some changes based on the Dijkstra algorithm. For example
And then list some short paths. Therefore, you can calculate the shortest path on the source image, delete an edge in the path, and re-calculate the shortest path in the remaining subgraph. In the original shortest path
You can obtain the Shortest Path of the subgraph after deleting the edge. These paths are sorted as a series of short paths of the source image.
The Open Shortest Path First (Open Shortest Path First) algorithm is a specific implementation of the Dijkstra Algorithm in network routing.
Unlike the Dijkstra algorithm, the bellman-Ford algorithm can be used in a graph with a negative spending edge, as long as the graph does not have a loop with a negative total cost and s reachable from the source point (if such a loop exists, then, the shortest path does not exist, because the total cost can be reduced without limit after multiple loops ).
One problem related to the shortest path problem is the traveling salesman problem (traveling salesman problem), which requires finding the shortest path that occurs exactly once through all vertices and eventually returns to the source point. This problem is NP-hard. In other words, unlike the shortest path problem, the traveling salesman problem is unlikely to have a polynomial time algorithm.
If the known information can be used to estimate the distance from a certain point to the target point, you can use the * algorithm to reduce the search range of the shortest path.