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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

#include

#include

#include

USINGNAMESPACESTD;

/**

* Author: Dmego

* Time: 2016-12-12

*/

#define MAX 1000000//represents maximum ∞

#define MAX 10

bools[max];//record from source point V0 to Endpoint VI is determined to be the shortest path, OK to remember true, or false

intpath[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 1

intd[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 Max

Typedefstruct

{

String vexs[max];//vertex table

intarcs[max][max];//adjacency Matrix

Intvexnum, arcnum;//current points and number of edges

}amgraph;

Using Dijkstra algorithm to find shortest path

Voidshortestpath_dij (Amgraph &g,intv0)

{////using the Dijkstra algorithm to find the shortest path of the V0 point to the remaining vertices in the network g

INTN = g.vexnum;//Top points

for (Intv = 0; v < n; v++)//n vertices are initialized sequentially

{

S[V] =false;//s initialized 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, the predecessor of V is initialized to V0

Else

PATH[V] = -1;//if V0 and V are boundless, initialize V's predecessor to-1

}

S[v0] =true;//adds V0 to S

D[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 array

for (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 V

v = w;

min = d[w];

}

S[V] =true;//adds v to the S set

for (INTW = 0; w < n; w++)

{//update the shortest path length from v0 to all vertices on the v-s set

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

Voidbackground ()

{

cout << "|*****************************************************************| 100= "" 125= "" 135= "" 140= "" 145= "" 150= "" 160= "" 200= "" 230= "" cout= ""------= "" >>> Please select: ";

}

Attractions Information Inquiry level two menu

Voidjmenu ()

{

cout << "|*****************************************************************| cout= "" >>> please check the number of attractions: ";

}

Shortest Path Query level two menu

Voidpmenu ()

{

cout << "|*****************************************************************| cout= "" >>> Please enter the start number and the end number in sequence: ";

}

Voidmain ()

{

Initialization operation

Amgraph 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 infinity

Adjacency 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 file

Ifstream 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;</div" m= "0;</div" end= "" temp1= "tem P "temp2=" Path[temp1];</div "temp=" Temp2;</div "i=" ">";

}

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 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.