C + + using Dijkstra (Dijkstra) algorithm to find the shortest path _c language

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 a note S[i]=true , no S[i]= flase ; an array of int type is Path[] used to record the direct precursor vertex number of VI on the current shortest path from V0 to VI, If the V to VI with the side of the Path[i] = v number, otherwise remembered Path[i] = -1 ; the last array d[] is used to record the shortest path length from V0 to VI, and the weights or weights of the sides of the V0 to VI are 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 , that is, 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:

#include <iostream> #include <fstream> #include <string> using namespace std; /** * Author: Dmego * Time: 2016-12-12/#define MAX 1000000//to represent Maxima ∞ #define MAX BOOL S[max]; Record from source point V0 to Endpoint VI has been determined to be the shortest path, OK to remember true, or false int path[max]; Record the direct precursor vertex number of the endpoint VI on the current shortest path from the source point V0 to the Endpoint VI, if the V0 to VI has a side precursor of V0 or 1 int d[max]; Record the length of the shortest path between the source point and the endpoint, the weight of the edge that is recorded V0 to VI, otherwise recorded as Max typedef struct {string Vexs[max];//vertex table int Arcs[max][max];//adjacency Matrix int Vexn Um, arcnum;
Figure current points and number of edges}amgraph;
 Using the Dijkstra algorithm to find the shortest path void Shortestpath_dij (amgraph &g, int v0) {//using the Dijkstra algorithm to find the shortest path int n = V0 top point in the net G of the g.vexnum;//to the remaining vertices  for (int v = 0; v < n; v++)//n vertices initialize {s[v] = false;//s Initialize to empty set d[v] = g.arcs[v0][v];//initializes the shortest path length v0 to each endpoint to a weighted value on the edge if
  (D[v] < MAX) PATH[V] = v0;//If there is an edge between V0 and V, initialize the predecessor of V to v0 else path[v] = -1;//Initialize the predecessor of V to-1} v0 If there is no boundless between s[v0 and V = true; Add V0 to s d[v0] = 0;//source point to Source point is 0//---------initialization ends, start the main loop, each time the shortest path to a vertex is v0, the V is added to the S array for (int i = 1; i < n; i++)//and sequentially to the remaining n
 1 vertices to compute {int min = MAX; int v = v0;
 for (int w = 0; w < n; w++) {if (!)
  S[W] && d[w] < min) {//Select a current shortest path, the end point is v = w;
  min = d[w]; } S[v] = true;//adds v to the S collection for (int w = 0; w < n; w++) {//update the shortest path length from v0 to all vertices on the collection v-s if (!
  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 function void BackGround () {cout << "|*****************************************************************|
 "<< Endl;
 cout << "|------------------------map-----------------|" << Endl;
 cout << "|*****************************************************************|" << Endl;  cout << "|
 ⑦ Unit: M | "<< Endl;  cout << "|
 Nine teaches | "<< Endl;  cout << "|
 ⑧| "<< Endl;  cout << "|
 ↗↖ Nine | "<< Endl; cout << "|
 ③200╱╲ | "<< Endl; cout << "|
 West ↙╲150↗↖| "<< Endl; cout << "| Screw ╲①160╱╲200 | " << Endl; cout << "|
 Field ↖150╲ information ⑥╱╲| "<< Endl; cout << "|
 ④↘140↘ College 200 ↙230↘| "<< Endl; cout << "|
 Gymnasium-------------→ ←--------------→ ←--------------→ | "<< endl;  cout << "|
 ↖↗↖↗↖↗②| "<< Endl;  cout << "|
 100╲╱╲125╱╲150╱ | "<< Endl;  cout << "|
 ↘↙100╲╱135╲╱145 Meal | "<< Endl;   cout << "|
 ↘↙↘↙| "<< Endl;  cout << "|
 ⑨ Qin Garden | "<< Endl;    cout << "|
 ⑩ Cui Yuan ⑤ chunhui Building | "<< Endl;        cout << "|
 | "<< Endl;

cout << "|*****************************************************************|" << Endl; }//Main menu void menu () {cout << "|*****************************************************************|" << Endl
 ;
 cout << "|----------------------------Iron Big Guide Small Program-----------------------|" << Endl; cout << "|*********************************************************|" &LT;&LT
 Endl
 cout << "|--------------------1-Attractions Information Inquiry--------------|" << Endl;
 cout << "|--------------------2-Shortest path Query--------------|" << Endl;
 cout << "|--------------------3-Show Sights View--------------|" << Endl;
 cout << "|-------------------4-Exit tour--------------|" << Endl;
 cout << "|*****************************************************************|" << Endl;
cout << ">>> Please select:"; //Attractions Information query level two menu void JMenu () {cout << "|*****************************************************************|" <
 < Endl;
 cout << "|-------------------------attractions Information Inquiry------------------------|" << Endl;
 cout << "|***********************************************************|" << Endl;
 cout << "|----------------------1-Information College Introduction-------------------|" << Endl;
 cout << "|----------------------2-Comprehensive Restaurant Introduction-------------------|" << Endl; cout << "|----------------------3-West Playground Introduction---------------------|
 "<< Endl;
 cout << "|----------------------4-Stadium Introduction---------------------|" << Endl;
 cout << "|----------------------5-Chunhui Building Introduction---------------------|" << Endl;
 cout << "|----------------------6-Introduction-----------------------|" << Endl;
 cout << "|----------------------7-Nine Teaching introduction-----------------------|" << Endl;
 cout << "|----------------------8-Nine-----------------------|" << Endl;
 cout << "|----------------------9-Qin yuan Introduction-----------------------|" << Endl;
 cout << "|---------------------10-cui Yuan-----------------------|" << Endl;
 cout << "|*****************************************************************|" << Endl;
cout << ">>> Please check the number of attractions:"; //Shortest Path query level two menu void Pmenu () {cout << "|*****************************************************************|" <
 < Endl; cout << "|-------------------------Shortest path Query------------------------|" << Endl
 cout << "|***********************************************************|" << Endl;
 cout << "|---------------------1-Information College-------------------|" << Endl; cout << "| --------------------2-Integrated Restaurant-------------------|
 "<< Endl;
 cout << "|---------------------3-West Playground---------------------|" << Endl;
 cout << "|---------------------4-Gymnasium---------------------|" << Endl;
 cout << "|---------------------5-Chunhui Building---------------------|" << Endl;
 cout << "|---------------------6-Fundamentalist-----------------------|" << Endl;
 cout << "|---------------------7-Nine teach-----------------------|" << Endl;
 cout << "|---------------------8-Nine-----------------------|" << Endl;
 cout << "|---------------------9-qin Yuan-----------------------|" << Endl;
 cout << "|--------------------10-Tsui Garden-----------------------|" << Endl; cout << "|**************************************| "<< Endl;
cout << >>> Please enter the start number and the end number in turn: "; } void Main () {//initialization operation Amgraph AMG = {"Information college", "comprehensive Restaurant", "" West Playground "," Gymnasium "," Chunhui House "," the Foundation teaches "," Nine teaches "," Nine "," Qin Yuan "," Cui Yuan "},//-1 represents both sides not Connected, the weight of infinite large//adjacency matrix//Letter to the Chunchi of the west of the Building qin Cui * * {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,M
 Ax,max,135,max,max,max,max}},10,14};
 int F, FF;
 int start, end;
 while (true) {cout << Endl;
 menu ();
 Cin >> F;
  if (f = = 1) {JMenu ();
       CIN >> FF;
  Attraction information read from the file ifstream outfile ("Schooltravel.txt", iOS:: Out | iOS:: binary); if (!outfile) {Cerr << "Failed to read the description file of the attraction!"
  "<< Endl;
  Abort ();
  } string Str[max];
  int i = 0;
  while (Getline (outfile, str[i++]);
  cout << "|-----------------------Attractions-------------------|" << Endl;
  if (ff = = 1) cout << str[0] << Endl;
  else if (ff = = 2) cout << str[1] << Endl;
  else if (ff = = 3) cout << str[2] << Endl;
  else if (ff = = 4) cout << str[3] << Endl;
  else if (ff = = 5) cout << str[4] << Endl;
  else if (ff = = 6) cout << str[5] << Endl;
  else if (ff = = 7) cout << str[6] << Endl;
  else if (ff = = 8) cout << str[7] << Endl;
  else if (ff = = 9) cout << str[8] << Endl;
  else if (ff = = ten) cout << str[9] << Endl;
 cout << "|-------------------------------------------------|" << Endl;
  else if (f = = 2) {pmenu ();
  CIN >> start >> end;
  Shortestpath_dij (AMG, start-1);
  int temp = end-1; int Temp1, TEMP2;
  int Flag[max], m = 0;
  cout << "from << Amg.vexs[start-1] <<" to "<< Amg.vexs[end-1] <<" Shortest path: ";
  while (temp!=-1) {flag[m++] = temp;
  Temp1 = temp;
  Temp2 = Path[temp1];
  temp = TEMP2;
  for (int i = m-1 i >= 0; i--) {cout <<amg.vexs[flag[i]] << "->";
  } cout << Endl;
 cout << "Shortest Path value is:" << d[end-1] << "M" << Endl;
 else if (f = = 3) {backGround (); else if (f = = 4) {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 Article

Contact Us

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.