The shortest path problem---Dijkstra algorithm to explain __ algorithm

Source: Internet
Author: User

Objective
Nobody can go back and start a new beginning,but anyone can-start and make a new ending.
Name:willam
Time:2017/3/8

1, the shortest Path problem introduction

Question Explanation:
The weight and the smallest path of the passing edge of another vertex from one vertex in the diagram, called the shortest path

Algorithm for solving problems: Dijkstra algorithm (Dijkstra algorithm) Freud algorithm (Floyd algorithm) SPFA algorithm

This blog, we will do a detailed introduction to the Dijkstra algorithm 2, Dijkstra algorithm introduction

Algorithm Features:

Dicos algorithm uses breadth-first search to solve the problem of single source shortest path with weighted direction graph or non direction graph, and finally obtains a shortest path tree. This algorithm is often used in routing algorithms or as a sub module of other graph algorithms.

The idea of the algorithm

The Dijkstra algorithm uses a greedy strategy that declares an array dis to hold the shortest distance from the source point to each vertex and a set of vertices where the shortest path is saved: T, at the beginning, the path weight of the Origin S is assigned to 0 (dis[s] = 0). If there is an edge (s,m) that can be reached directly for vertex s existence, the dis[m] is set to W (S, m), while the path length of all other vertices (s that cannot be reached directly) is set to infinity. Initially, the set T is only vertex s.
Then, by selecting the minimum value from the DIS array, the value is the shortest path from the source point S to the vertex of the value, and the point is added to T, OK, to complete a vertex at this time,
Then we need to see if the newly added vertices can reach the other vertices and see if the path lengths to other points through the vertices are shorter than the source points, and if so, replace the vertices in dis.
Then, we find the minimum value from dis and repeat the above action until T contains all the vertices of the graph. 3, Dijkstra algorithm example demo

Below I seek the following figure, from the vertex v1 to the other vertices of the shortest path

First of all, let's first declare a dis array that initializes the values:

Our vertex set T is initialized to: T={v1}

Since it is the shortest distance from the V1 vertex to the rest of the vertices, find a vertex nearest to the 1th vertex. It is known from the array dis that the V1 vertex is the V3 vertex recently. When the number 2nd vertex is selected, the value of dis[2] (the subscript starting from 0) has changed from "Estimated value" to "fixed value", i.e. the shortest distance from the V1 vertex to the V3 vertex is the current dis[2 value. Add V3 to T.
Why , why? Since the closest vertex to the V1 vertex is v3, and all sides of the graph are positive, it is certainly not possible to pass through the third vertex, making the V1 vertex to the V3 vertex further shortened. Because the distance from the V1 vertex to the other vertex is certainly not v1 to the V3 vertex short.

OK, now that you've determined the shortest path to a vertex, below we have to according to this new vertex V3 will have a degree, found that V3 for the arc of the tail is: < V3,V4, then we look at the path: v1–v3–v4 length is shorter than the v1–v4, in fact this is already very obvious, Because Dis[3] represents the length of the v1–v4 is infinitely large, and the length of the V1–V3–V4 is: 10+50=60, so update the value of dis[3], get the following results:

Therefore dis[3] is to be updated to 60. This process has a technical term called "slack". That is, the V1 vertex to the V4 vertex of the distance is dis[3], through the < v3,v4> this edge slack success. This is the main idea of the Dijkstra algorithm: "Edge" to relax the V1 vertex to the rest of the vertices of the distance.

Then, we look for the smallest value from other values except dis[2] and dis[0], and we find that the value of dis[4] is minimal, by the principle of interpretation, the shortest distance v1 to V5 is the value of dis[4, and then we add V5 to the set T, and then, Considering whether the V5 will affect the value of our array dis, V5 has two degrees:< v5,v4> and < V5,v6>, and then we find that: the v1–v5–v4 length is 50, and dis[3] is 60, so we want to update dis[3] In addition, the length of the V1-V5-V6 is: 90, and dis[5] is 100, so we need to update the value of Dis[5]. The updated DIS array is shown below:

Then, continue to select a minimum value from the value of the indeterminate vertex in dis and find that the value of dis[3] is the smallest, so add the V4 to the set T, then set T={V1,V3,V5,V4}, and then, consider whether the V4 degree will affect the value of our array dis. V4 has a degree of:< V4,v6>, and then we find that: the V1–V5–V4–V6 length is: 60, and the dis[5] value is 90, so we want to update the value of Dis[5], the updated DIS array is as follows:

Then we use the same principle to determine the shortest path of V6 and V2, respectively, and the values of the last dis array are as follows:

So, from the diagram, we can find that the value of V1-v2 is: ∞, which represents no path from V1 to v2. So the final result we got was:

Start  end    Shortest path    length
v1    v2     no          ∞    
      v3     {v1,v3}
      v4     {V1,V5,V4}  50
      V5     {V1,V5}
      V6     {V1,V5,V4,V6} 60
4, Dijkstra Algorithm code implementation (c + +)Code for DIJKSTRA.H files
/************************************************************//* Program Author: Willam * */ * Program Completion time: 2017/3/8////* have any questions please contact: 2930526477@qq.com * */************ ///@ as far as possible to write the perfect program #pragma once//#pragma once is a more commonly used C + + pragma,//

As long as you add this pragma to the beginning of the header file,//You can guarantee that the header file is compiled only once.

#include <iostream> #include <string> using namespace std;
    * This program is to use the Dijkstra algorithm to solve the problem of the shortest path using the adjacency matrix to store the map//record starting point to the shortest path to each vertex information struct Dis {string path;
    int value;
    BOOL visit;
        Dis () {visit = false;
        Value = 0;
    Path = "";

}
};   Class GRAPH_DG {Private:int vexnum;     The number of vertices of the graph int edge;   The number of sides of the graph int **arc;   adjacency Matrix dis * DIS;
    Record information for the shortest path of each vertex public://constructor GRAPH_DG (int vexnum, int edge);
    Destructors ~GRAPH_DG ();
    Determine if the information we entered at each edge is legitimate//vertex numbered from 1 bool Check_edge_value (int start, int end, int weight);
 Create diagram   void Creategraph ();
    Print adjacency matrix void print ();
    Find the shortest path void Dijkstra (int begin);
Print Shortest path void print_path (int);
 };
Code for Dijkstra.cpp files
#include "Dijkstra.h"//constructor GRAPH_DG::GRAPH_DG (int vexnum, int edge) {//Initialize vertex number and number of edges this->vexnum = Vexnum;
    This->edge = Edge;
    Open space for adjacency matrices and assign initial value arc = new int*[this->vexnum];
    dis = new dis[this->vexnum];
        for (int i = 0; i < this->vexnum; i++) {Arc[i] = new int[this->vexnum];
        for (int k = 0; k < this->vexnum; k++) {//adjacency matrix initialized to infinity arc[i][k] = Int_max;
    }}//destructor GRAPH_DG::~GRAPH_DG () {delete[] dis;
    for (int i = 0; i < this->vexnum; i++) {Delete this->arc[i];
} Delete arc; //Determine if the information we entered at the edges is valid//vertex numbered from 1 bool Graph_dg::check_edge_value (int start, int end, int weight) {if start<1 | | end<1 | | Start>vexnum | | End>vexnum | |
    Weight < 0) {return false;
return true;
    } void Graph_dg::creategraph () {cout << "Enter the starting and ending points for each edge (vertex numbering starts with 1) and its weight" << Endl;
    int start;
    int end;
    int weight;int count = 0;
        while (Count!= This->edge) {cin >> start >> end >> weight; First of all, determine if the edge information is legitimate while (!this->check_edge_value (start, end, weight)) {cout << "entered the edge of the information is illegal, please lose again
            into "<< Endl;
        CIN >> start >> end >> weight;
        ///The point assignment on the adjacency matrix arc[start-1][end-1] = weight;
        This line of code is added to the//arc[end-1][start-1 graph] = weight;
    ++count;
    } void Graph_dg::p rint () {cout <<) the adjacency matrix of the graph is: << Endl; int count_row = 0; The label of the print line int count_col = 0;
        Print the label of the column//start printing while (Count_row!= this->vexnum) {count_col = 0;  while (Count_col!= this->vexnum) {if (arc[count_row][count_col] = = Int_max) cout <<
            "∞" << "";
            else cout << Arc[count_row][count_col] << "";
        ++count_col;
        } cout << Endl; ++cOunt_row;
    } void Graph_dg::D ijkstra (int begin) {//First initialize our dis array int i; for (i = 0; i < this->vexnum; i++) {//Set the current path Dis[i].path = "V" + to_string (BEGIN) + "-->v" + to
        _string (i + 1);
    Dis[i].value = Arc[begin-1][i];
    //sets the path to the beginning of the starting point for 0 dis[begin-1].value = 0;

    Dis[begin-1].visit = true;
    int count = 1; Calculates the shortest path of the remaining vertices (the remaining this->vexnum-1 vertices) while (count!= this->vexnum) {//temp is used to hold the lowest subscript//In the current dis array.
        Min Record of the current minimum value int temp=0;
        int min = Int_max;
                for (i = 0; i < this->vexnum; i++) {if (!dis[i].visit && dis[i].value<min) {
                min = Dis[i].value;
            temp = i;
        }//cout << temp + 1 << "" <<min << Endl;
        Add the vertices corresponding to the temp to the set of the shortest path that has been found dis[temp].visit = true;
        ++count; for (i = 0; i < this->vexnum; i++) {//Note the conditions here arc[Temp][i]!=int_max must be added, otherwise there will be overflow, resulting in program exceptions if (!dis[i].visit && arc[temp][i]!=int_max && (dis[temp) . Value + arc[temp][i]) < Dis[i].value) {//If the newly obtained edge can affect other vertices that are accessed, then update its shortest path and length Dis[i].va
                Lue = Dis[temp].value + arc[temp][i];
            Dis[i].path = Dis[temp].path + "-->v" + to_string (i + 1);
    }} void Graph_dg::p rint_path (int begin) {string str;
    str = "V" + to_string (begin);
    cout << "<<str<<" as the starting point of the shortest path of the chart is: "<< Endl; for (int i = 0; I!= this->vexnum; i++) {if (Dis[i].value!=int_max) cout << Dis[i].path <<
        "=" << dis[i].value << Endl;
        else {cout << dis[i].path << "is no shortest path" << Endl; }
    }
}
Code for main.cpp files
#include "Dijkstra.h"//


Check the value of the number of input edges and vertices is valid, you can calculate why:
//vertex number and edge number of the relationship is: ((vexnum* (Vexnum-1))/2) < edge
BOOL Check (int vexnum, int edge) {
    if (vexnum <= 0 | | Edge <= 0 | | ((vexnum* (Vexnum-1)/2) < edge) return
        false;
    return true;
}
int main () {
    int vexnum; int edge;

    cout << "number of vertices and edges of the input graph:" << Endl;
    Cin >> vexnum >> Edge;
    while (!check (Vexnum, Edge)) {
        cout << "The value entered is not valid, please re-enter" << Endl;
        Cin >> vexnum >> Edge;
    }
    GRAPH_DG graph (Vexnum, edge);
    Graph.creategraph ();
    Graph.print ();
    Graph. Dijkstra (1);
    Graph.print_path (1);
    System ("pause");
    return 0;
}

Input:

6 8
1 3
1 5
1 6 2 3
5 3 4 4 6 5 6

Output:

As you can see from the output, the results of the program are the same as the results we manually calculated before.

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.