The daily walkthrough of the classic Algorithm problem--the 17th problem Dijkstra algorithm

Source: Internet
Author: User

The original: A daily walkthrough of the classic Algorithm--the 17th Dijkstra algorithm

Perhaps in life, often encounter against a problem, under the numerous constraints, how to find an optimal solution? You might think of a lot of things like "linear programming," "Dynamic planning."

These classical strategies, of course, some problems we can use greed to find the overall optimal solution, in graph theory, a typical greedy method to find the best solution is the "shortest path" problem.

One: the approximate order

From which I am looking for the shortest path to V0 to V3, you will find a lot of two points to their path: v0->v4->v3,v0->v1->v3, of course you will think the former is the shortest you are looking for

Path, so if you say that there are so many vertices, will you find it so easily? Now we are going to put our greedy thinking system under the arrangement.

Two: Build

If you already know the prim algorithm, then the Dijkstra algorithm is just above its extension, in fact, it is very simple.

1. Edge Node

A little bit different here is that I define a vertexs on the edge to record greedy search to a node when the node has traversed, such as from V0 greedy search to V3, we V3

Vertexs may hold v0,v4,v3 these past nodes, perhaps the last of these three nodes is the shortest path we are looking for.

1 #region Side Information 2         //<summary> 3         ///SIDE Information 4         //</summary> 5 Public         class Edge 6         {7             / /Start side 8 public             int Startedge; 9             //end edge one public             int endedge;12             //weight of public int             weight;15 16
   //whether to use the public             bool isuse;18             //cumulative vertex public             hashset<int> vertexs = new hashset<int> ();         }22         #endregion

2.Dijkstra algorithm

First we analyze the steps of the Dijkstra algorithm:

There are sets of m={v0,v1,v2,v3,v4} Such 5 elements that we use

Tempvertex Indicates whether the vertex is used.

Weight represents the weight of the path (default is MaxValue).

Path represents the total weight of the vertex.

①. Select the vertex V0 from the set m as the starting point. Assign values to all adjacency points of the V0, assuming that the weight to be assigned is smaller than the original weight, and that the

Vertex, and then picks the current smallest weight as the starting point for the next greedy search, so that the V0V1 is selected for the shortest path, 2.

②. We continue to assign values to the adjacency point in the same way from the vertex of V1, and finally we find that the v0v4 is the shortest path. That is Figure 3.

。。。

③. The shortest path to all the last vertices is then calculated.

 1 #region Dijkstra algorithm 2//<summary> 3//Dijkstra algorithm 4//</summary> 5 Publ IC Dictionary<int, edge> Dijkstra () 6 {7//collect vertices adjacent edges 8 dictionary<int, edge> D Ic_edges = new Dictionary<int, edge> ();                 9//weight=maxvalue: Logo no edge one for (int i = 0; i < graph.vertexsnum; i++) 12 {13 Start side var Startedge = i;15 dic_edges. ADD (Startedge, New Edge () {weight = Int. MaxValue}); 17}18 19//Take first vertex var start = 0;21 for (int i = 0; I &lt ; Graph.vertexsnum;                 i++) 23 {24//mark the vertex has been used over dic_edges[start].isuse = true;26 27                     for (int j = 1; j < Graph.vertexsnum; J + +)-{var end = J;30 31 The weight of the adjacent edge is taken from the var weight = Graph.edges[start, end];33 34//Assign a smaller weight of the IF (weight < dic_edges[end].weight) 36 {37 The weight of the previous vertex is incremented by the sum of var totalweight = Dic_edges[start].weight = = Int. MaxValue?                         Weight:dic_edges[start].weight + weight;39 (Totalweight < dic_edges[end].weight) 41 {42//Add adjacent edges of the vertex to the collection dic_edges[end] = new Ed                                 GE () Startedge = start,46                             Endedge = end,47 weight = totalweight48};49 50 The vertex of the node on the previous edge is incremented by Dic_edges[end].vertexs = new Hashset<int> (Dic_edge S[START].VERTEXS); Dic_edges[end].vertexs. ADD (start); Dic_edges[end].vertexs. ADD (End),}56}57}58, var min = Int.                 MAXVALUE;60 61//Next vertex to compare Minkey = 0;63 64//Take the minimum value of the start adjacency Edge 65 foreach (Var key in Dic_edges. Keys) 66 {67//take the current smallest key (except used) if (min > Dic_edges[key].we                         ight &&!dic_edges[key].isuse) (min. = dic_edges[key].weight;71)                 Minkey = key;72}73}74 75//From the vertex of the adjacent edge and start looking for 76 Start = minkey;77}78 return dic_edges;80}81 #endregion

Total code: The complexity is very bad O (N2) ...

Using system;using system.collections.generic;using system.linq;using system.text;using System.Diagnostics;using        System.threading;using system.io;using system.threading.tasks;namespace consoleapplication2{public class Program { public static void Main () {dictionary<int, string> dic = new Dictionary<int, string>            ();            Matrixgraph graph = new Matrixgraph (); Graph.            Build (); var result = Graph.            Dijkstra ();            Console.WriteLine ("The shortest path for each node is:"); foreach (var key in result.) Keys) {Console.WriteLine ("{0}", String.            Join ("--", Result[key].vertexs));        } console.read ();        }} #region define a matrix node///<summary>//define Matrix node///</summary> public class Matrixgraph {        Graph graph = new graph ();            public class Graph {//<summary>///vertex info//</summary> PublicInt[] Vertexs;            <summary>////</summary> public int[,] edges;            <summary>///number of vertices///</summary> public int vertexsnum;        <summary>///number of edges///</summary> public int edgesnum;        The construction of the #region Matrix///<summary>/////</summary> public void Build ()            {//Vertex number graph.vertexsnum = 5;            Number of sides Graph.edgesnum = 6;            Graph.vertexs = new Int[graph.vertexsnum];            Graph.edges = new Int[graph.vertexsnum, Graph.vertexsnum]; Constructs a two-dimensional array for (int i = 0; i < Graph.vertexsnum; i++) {//Vertex graph.ve                Rtexs[i] = i; for (int j = 0; J < Graph.vertexsnum; J + +) {graph.edges[i, j] = Int.  MaxValue;              }}//define 6 edges graph.edges[0, 1] = graph.edges[1, 0] = 2;            Graph.edges[0, 2] = graph.edges[2, 0] = 5;            Graph.edges[0, 4] = graph.edges[4, 0] = 3;            Graph.edges[1, 3] = graph.edges[3, 1] = 4;            Graph.edges[2, 4] = graph.edges[4, 2] = 5;        Graph.edges[3, 4] = graph.edges[4, 3] = 2; } #endregion information for #region//<summary>/////</summary> Publ            IC class Edge {//Start side public int startedge;            End Edge public int endedge;            Weight public int weight;            Whether to use public bool isuse;        Cumulative vertex public hashset<int> Vertexs = new hashset<int> ();         } #endregion #region Dijkstra algorithm//<summary>//Dijkstra algorithm///</summary> Public Dictionary<int, Edge> Dijkstra () {            Collect vertices of adjacent edges dictionary<int, edge> dic_edges = new Dictionary<int, edge> ();                Weight=maxvalue: Identity without edge for (int i = 0; i < Graph.vertexsnum; i++) {//Start side                var Startedge = i; Dic_edges. ADD (Startedge, New Edge () {weight = Int.            MaxValue});            }//Take the first vertex var start = 0; for (int i = 0; i < Graph.vertexsnum; i++) {//mark the vertex has been used Dic_edges[start].isu                Se = true;                    for (int j = 1; j < Graph.vertexsnum; J + +) {var end = J;                    The weighted var weight = Graph.edges[start, end] taken to the neighboring edge; Assigns a lower weight if (weight < Dic_edges[end].weight) {//Weights to previous vertex accumulate var totalweight = Dic_edges[start].weight = = Int. MaxValue? Weight:dic_edges[start]. Weight + weight;                            if (Totalweight < dic_edges[end].weight) {//Adds adjacent edges of the vertex to the collection Dic_edges[end] = new Edge () {Startedge = Star                            T, Endedge = end, weight = Totalweight                            };                            Adds the vertex of the node on the previous edge Dic_edges[end].vertexs = new hashset<int> (DIC_EDGES[START].VERTEXS); Dic_edges[end].vertexs.                            ADD (start); Dic_edges[end].vertexs.                        ADD (end); }}} var min = Int.                MaxValue;                The next vertex to compare is int minkey = 0; Take the minimum value of the Start adjacency edge, foreach (Var key in Dic_edges.            Keys) {//Take the current smallest key (except used)        if (min > Dic_edges[key].weight &&!dic_edges[key].isuse) {m                        in = Dic_edges[key].weight;                    Minkey = key;            }}//From the vertex of the adjacent edge and start looking for start = Minkey;        } return dic_edges; } #endregion} #endregion}

  

The daily walkthrough of the classic Algorithm problem--the 17th problem Dijkstra algorithm

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.