# An algorithm for solving shortest path with Dijkstra (Dijkstra) in C + +

Source: Internet
Author: User

Algorithm Introduction

The Dijkstra algorithm was proposed by the Dutch computer scientist Dixtra in 1959, and is therefore called the Dixtra algorithm. is the shortest path algorithm from a vertex to the rest of the vertices, and solves the problem of the shortest path in the direction graph. The main feature of the Dijkstra algorithm is to extend the starting point to the outer layer until the end is extended. Dijkstra algorithm can get the optimal solution of shortest path, but it is inefficient because it traverses many nodes of computation.

Algorithm idea

Increment order generation algorithm by path length:

Divide the vertex set V into two groups:

(1) S: The set of vertices that have been evaluated (initially containing only the source point V0)

(2) V-s=t: Set of vertices not yet determined
Adds the vertices in t to s in ascending order to ensure that:

(1) The length of the other vertices from the source point V0 to S is not more than the shortest path length from the V0 to any vertices in t

(2) Each vertex corresponds to a distance value

s in vertices: from V0 to the length of this vertex

T Middle Vertex: The shortest path length from V0 to this vertex that includes only s in vertices as intermediate vertices

Basis: It can be proved that the V0 to the vertex VK in T, or the right value of the direct path from V0 to VK, or the sum of the path weights from the V0 to the vertex to the VK

Application examples

(1) Topic: the preparation of a campus tour guide program for visitors to provide a variety of information inquiries services.

Main functions: 1. Design School Campus plan, contains not less than 10 scenic spots: Vertex to indicate the scenic spots, the edge of the path;

2. To provide visitors with information on any attractions in the map of the query;

3. To provide guests with any scenic spots in the query, that is, the search for people with a shortest route between the attractions.

Requirements: 1. Design a main interface;

2. Design function menu for users to choose

3. There is a certain practicality.

(2) Design ideas:

1, this question mainly has the algorithm thought as well as the procedure logical thought, first from the logic of the idea, access to the program, first design a main menu, options have attractions information query, the shortest path query and display the view of the plane views of three submenu, and then according to the user's input selected submenu before the number, divided into different submenus ; This feature is made by If....else if .... Statement implementation. In the scenic Spot information query and the shortest Path Query submenu, there are two levels of submenu, are listed all the sights and in front of the number, query the attractions information, enter the number of scenic spots before, query the shortest path, enter the starting point number, and then enter the end of the number. And the view of the display of the attractions call the attraction map function to display.

2, the algorithm is mainly the idea of Dijkstra algorithm, using Dijkstra algorithm to find the shortest path.

3, the first definition of a good diagram of the storage structure, the subject of the adjacency matrix to represent the graph, and in the main function initialization of the diagram;

4, the definition of three global one-dimensional array, a bool type array s[] used to record from V0 to VI whether the shortest path has been determined, is the s[i]=true, do not remember s[i]= flase; an array of int types path[] Used to record the direct precursor vertex number of VI on the current shortest path from V0 to VI, if there is an edge between V to VI path[i] = V's number, otherwise remember path[i] =-1; the last array d[] is used to record the shortest path length between v0 and VI, The existence of the v0 to VI to the edge of the weight or weight value and, otherwise recorded as Max

5. Define a function to find the shortest path, the incoming parameter is the diagram and the starting point, first carries on the initialization work, initializes the s[] array to initialize to the beginning to each vertex the weight value, the path[] array initializes the beginning whether with each vertex has the edge, has the memory v0 otherwise to remember-1;

6, and then carry out n-1 for the loop, find the shortest path between VO and the rest of the n-1 vertices, compare the minimum value in the current d[] array, find the smallest number V, which is the number of vertices from v0 to the shortest distance from all vertices, and then set the value of S[v to true. The shortest path is found from v0 to Vertex v;

7, then update the d[] array, because the d[] array is the shortest path record, now that the shortest path to a vertex has been found, the vertex v is the middle point, and the path length from the vertex v to the remaining vertex, plus the path length from the point to the V0, is less than the length of the path directly from V0 to the rest of the vertices. , if less than, the update d[i] is the length of the path evaluated with the vertex v as the middle point. Update path[i] = V; the precursor of I is no longer v0 but V;

8, Loop (6) (7) Two steps n-1 to get d[] array, output d[] array is both v0 to all vertices shortest path length;

(3) Source code:

 123456789101112131415161718192021st222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232 #include #include #include USINGNAMESPACESTD;/*** Author: Dmego* Time: 2016-12-12*/#define MAX 1000000//represents maximum ∞#define MAX 10bools[max];//record from source point V0 to Endpoint VI is determined to be the shortest path, OK to remember true, or falseintpath[max];//records the direct precursor vertex number of Endpoint VI on the current shortest path from source point V0 to Endpoint VI, if V0 to VI has edge precursor to V0 otherwise 1intd[max];//record the length of the shortest path between the source point and the endpoint, the right value of the side that V0 to VI, otherwise recorded as MaxTypedefstruct{String vexs[max];//vertex tableintarcs[max][max];//adjacency MatrixIntvexnum, arcnum;//current points and number of edges}amgraph;Using Dijkstra algorithm to find shortest pathVoidshortestpath_dij (Amgraph &g,intv0){////using the Dijkstra algorithm to find the shortest path of the V0 point to the remaining vertices in the network gINTN = g.vexnum;//Top pointsfor (Intv = 0; v < n; v++)//n vertices are initialized sequentially{S[V] =false;//s initialized to empty setD[V] = g.arcs[v0][v];//initializes the shortest path length v0 to each endpoint to a weighted value on the edgeif (D[v] < MAX)PATH[V] = v0;//If there is an edge between V0 and V, the predecessor of V is initialized to V0ElsePATH[V] = -1;//if V0 and V are boundless, initialize V's predecessor to-1}S[v0] =true;//adds V0 to SD[v0] = 0;//source point to Source point has a weight value of 0---------initialization ends, start the main loop, and each time the shortest path to a vertex is v0, the V is added to the S arrayfor (inti = 1; i < n; i++)//To compute the remaining n-1 vertices in turn{Intmin = MAX;Intv = V0;for (INTW = 0; w < n; w++){if (! S[W] && d[w] < min){//Select a current shortest path with end point Vv = w;min = d[w];}S[V] =true;//adds v to the S setfor (INTW = 0; w < n; w++){//update the shortest path length from v0 to all vertices on the v-s setif (! S[W] && (D[v] + g.arcs[v][w] < d[w)){D[W] = d[v] + g.arcs[v][w];//update d[w]PATH[W] = v;//Change the predecessor of W to V}}}}}Background functionVoidbackground (){cout << "|*****************************************************************| 100= "" 125= "" 135= "" 140= "" 145= "" 150= "" 160= "" 200= "" 230= "" cout= ""------= "" >>> Please select: "; }Attractions Information Inquiry level two menuVoidjmenu (){cout << "|*****************************************************************| cout= "" >>> please check the number of attractions: "; }Shortest Path Query level two menuVoidpmenu (){cout << "|*****************************************************************| cout= "" >>> Please enter the start number and the end number in sequence: "; }Voidmain (){Initialization operationAmgraph AMG = {"Information college", "comprehensive Restaurant", "West Playground", "Gymnasium", "Chunhui House","The Foundation teaches", "Nine teaches", "Nine Buildings", "Qin Yuan", "Cui Yuan"},-1 represents the two sides are not connected, the weight of infinityAdjacency Matrix/* Letter Chunchi{{max,max,max,140,max,200,150,max,100,125},{Max,max,max,max,145,230,max,100,max,max},{Max,max,max,150,max,max,200,max,max,max},{140,max,150,max,max,max,max,max,100,max},{Max,145,max,max,max,150,max,max,max,max},{200,230,max,max,150,max,max,160,max,135},{150,max,200,max,max,max,max,max,max,max},{Max,200,max,max,max,160,max,max,max,max},{100,max,max,100,max,max,max,max,max,max},{125,max,max,max,max,135,max,max,max,max}},10,14};INTF, FF;Intstart, end;while (true){cout << Endl;menu ();Cin >> F;if (f = = 1){JMenu ();CIN >> FF;Attraction information read from the fileIfstream outfile ("Schooltravel.txt", iOS:: Out | iOS:: binary);if (!outfile){Cerr << "Read the introduction file of the attraction failed!" string= "" inti= "M-1" cout= "" ff= "=" f= "=" cin= "" start= "" = "" inttemp= "End-1;"; }cout << Endl;cout << "Shortest Path value is: end=" "=" "f=" = "cout=" >>> exit successful! "<< Endl; Exit (0);}}}

(4) Run screenshot:

Summarize

The above is about C + + with Dijkstra algorithm (Dijkstra algorithm) to find the shortest path of all the content, I hope this article on the content of everyone's study or work to bring certain help, if you have questions you can message exchange.

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.