算法系列15天速成——第十五天 圖【下】(大結局)


 

    今天是大結局,說下“圖”的最后一點東西,“最小生成樹“和”最短路徑“。

 

一: 最小生成樹

1. 概念

    首先看如下圖,不知道大家能總結點什么。

    對於一個連通圖G,如果其全部頂點和一部分邊構成一個子圖G1,當G1滿足:

       ① 剛好將圖中所有頂點連通。②頂點不存在回路。則稱G1就是G的“生成樹”。

           其實一句話總結就是:生成樹是將原圖的全部頂點以最小的邊連通的子圖,這不,如下的連通圖可以得到下面的兩個生成樹。

       ② 對於一個帶權的連通圖,當生成的樹不同,各邊上的權值總和也不同,如果某個生成樹的權值最小,則它就是“最小生成樹”。

     

2. 場景

      實際應用中“最小生成樹”還是蠻有實際價值的,教科書上都有這么一句話,若用圖來表示一個交通系統,每一個頂點代表一個城市,

  邊代表兩個城市之間的距離,當有n個城市時,可能會有n(n-1)/2條邊,那么怎么選擇(n-1)條邊來使城市之間的總距離最小,其實它

  的抽象模型就是求“最小生成樹”的問題。

 

3. prim算法

    當然如何求“最小生成樹”問題,前人都已經給我們總結好了,我們只要照葫蘆畫瓢就是了,

    第一步:我們建立集合“V,U",將圖中的所有頂點全部灌到V集合中,U集合初始為空。

    第二步: 我們將V1放入U集合中並將V1頂點標記為已訪問。此時:U(V1)。

    第三步: 我們尋找V1的鄰接點(V2,V3,V5),權值中發現(V1,V2)之間的權值最小,此時我們將V2放入U集合中並標記V2為已訪問,

                此時為U(V1,V2)。

    第四步: 我們找U集合中的V1和V2的鄰接邊,一陣痙攣后,發現(V1,V5)的權值最小,此時將V5加入到U集合並標記為已訪問,此時

                 U的集合元素為(V1,V2,V5)。

    第五步:此時我們以(V1,V2,V5)為基准向四周尋找最小權值的鄰接邊,發現(V5,V4)的權值最小,此時將V4加入到U集合並標記

                 為已訪問,此時U的集合元素為(V1,V2,V5,V4)。

    第六步: 跟第五步形式一樣,找到了(V1,V3)的權值最小,將V3加入到U集合中並標記為已訪問,最終U的元素為(V1,V2,V5,V4,V3),

                最終發現頂點全部被訪問,最小生成樹就此誕生。

 1 #region prim算法獲取最小生成樹
2 /// <summary>
3 /// prim算法獲取最小生成樹
4 /// </summary>
5 /// <param name="graph"></param>
6 public void Prim(MatrixGraph graph, out int sum)
7 {
8 //已訪問過的標志
9 int used = 0;
10
11 //非鄰接頂點標志
12 int noadj = -1;
13
14 //定義一個輸出總權值的變量
15 sum = 0;
16
17 //臨時數組,用於保存鄰接點的權值
18 int[] weight = new int[graph.vertexNum];
19
20 //臨時數組,用於保存頂點信息
21 int[] tempvertex = new int[graph.vertexNum];
22
23 //取出鄰接矩陣的第一行數據,也就是取出第一個頂點並將權和邊信息保存於臨時數據中
24 for (int i = 1; i < graph.vertexNum; i++)
25 {
26 //保存於鄰接點之間的權值
27 weight[i] = graph.edges[0, i];
28
29 //等於0則說明V1與該鄰接點沒有邊
30 if (weight[i] == short.MaxValue)
31 tempvertex[i] = noadj;
32 else
33 tempvertex[i] = int.Parse(graph.vertex[0]);
34 }
35
36 //從集合V中取出V1節點,只需要將此節點設置為已訪問過,weight為0集合
37 var index = tempvertex[0] = used;
38 var min = weight[0] = short.MaxValue;
39
40 //在V的鄰接點中找權值最小的節點
41 for (int i = 1; i < graph.vertexNum; i++)
42 {
43 index = i;
44 min = short.MaxValue;
45
46 for (int j = 1; j < graph.vertexNum; j++)
47 {
48 //用於找出當前節點的鄰接點中權值最小的未訪問點
49 if (weight[j] < min && tempvertex[j] != 0)
50 {
51 min = weight[j];
52 index = j;
53 }
54 }
55 //累加權值
56 sum += min;
57
58 Console.Write("({0},{1}) ", tempvertex[index], graph.vertex[index]);
59
60 //將取得的最小節點標識為已訪問
61 weight[index] = short.MaxValue;
62 tempvertex[index] = 0;
63
64 //從最新的節點出發,將此節點的weight比較賦值
65 for (int j = 0; j < graph.vertexNum; j++)
66 {
67 //已當前節點為出發點,重新選擇最小邊
68 if (graph.edges[index, j] < weight[j] && tempvertex[j] != used)
69 {
70 weight[j] = graph.edges[index, j];
71
72 //這里做的目的將較短的邊覆蓋點上一個節點的鄰接點中的較長的邊
73 tempvertex[j] = int.Parse(graph.vertex[index]);
74 }
75 }
76 }
77 }
78 #endregion


二: 最短路徑

1.   概念

        求最短路徑問題其實也是非常有實用價值的,映射到交通系統圖中,就是求兩個城市間的最短路徑問題,還是看這張圖,我們可以很容易的看出比如

     V1到圖中各頂點的最短路徑。

      ① V1  ->  V2              直達,     權為2。

      ② V1  ->  V3              直達        權為3。

      ③ V1->V5->V4           中轉       權為3+2=5。

      ④ V1  ->  V5               直達      權為3。

 

2.  Dijkstra算法

      我們的學習需要站在巨人的肩膀上,那么對於現實中非常復雜的問題,我們肯定不能用肉眼看出來,而是根據一定的算法推導出來的。

  Dijkstra思想遵循 “走一步,看一步”的原則。

     第一步: 我們需要一個集合U,然后將V1放入U集合中,既然走了一步,我們就要看一步,就是比較一下V1的鄰接點(V2,V3,V5),

                 發現(V1,V2)的權值最小,此時我們將V2放入U集合中,表示我們已經找到了V1到V2的最短路徑。

     第二步:然后將V2做中間點,繼續向前尋找權值最小的鄰接點,發現只有V4可以連通,此時修改V4的權值為(V1,V2)+(V2,V4)=6。

                此時我們就要看一步,發現V1到(V3,V4,V5)中權值最小的是(V1,V5),此時將V5放入U集合中,表示我們已經找到了

                V1到V5的最短路徑。

     第三步:然后將V5做中間點,繼續向前尋找權值最小的鄰接點,發現能連通的有V3,V4,當我們正想修該V3的權值時發現(V1,V3)的權值

                小於(V1->V5->V3),此時我們就不修改,將V3放入U集合中,最后我們找到了V1到V3的最短路徑。

     第四步:因為V5還沒有走完,所以繼續用V5做中間點,此時只能連通(V5,V4),當要修改權值的時候,發現原來的V4權值為(V1,V2)+(V2,V4),而

                現在的權值為5,小於先前的6,此時更改原先的權值變為5,將V4放入集合中,最后我們找到了V1到V4的最短路徑。

 

 1 #region dijkstra求出最短路徑
2 /// <summary>
3 /// dijkstra求出最短路徑
4 /// </summary>
5 /// <param name="g"></param>
6 public void Dijkstra(MatrixGraph g)
7 {
8 int[] weight = new int[g.vertexNum];
9
10 int[] path = new int[g.vertexNum];
11
12 int[] tempvertex = new int[g.vertexNum];
13
14 Console.WriteLine("\n請輸入源點的編號:");
15
16 //讓用戶輸入要遍歷的起始點
17 int vertex = int.Parse(Console.ReadLine()) - 1;
18
19 for (int i = 0; i < g.vertexNum; i++)
20 {
21 //初始賦權值
22 weight[i] = g.edges[vertex, i];
23
24 if (weight[i] < short.MaxValue && weight[i] > 0)
25 path[i] = vertex;
26
27 tempvertex[i] = 0;
28 }
29
30 tempvertex[vertex] = 1;
31 weight[vertex] = 0;
32
33 for (int i = 0; i < g.vertexNum; i++)
34 {
35 int min = short.MaxValue;
36
37 int index = vertex;
38
39 for (int j = 0; j < g.vertexNum; j++)
40 {
41 //頂點的權值中找出最小的
42 if (tempvertex[j] == 0 && weight[j] < min)
43 {
44 min = weight[j];
45 index = j;
46 }
47 }
48
49 tempvertex[index] = 1;
50
51 //以當前的index作為中間點,找出最小的權值
52 for (int j = 0; j < g.vertexNum; j++)
53 {
54 if (tempvertex[j] == 0 && weight[index] + g.edges[index, j] < weight[j])
55 {
56 weight[j] = weight[index] + g.edges[index, j];
57 path[j] = index;
58 }
59 }
60 }
61
62 Console.WriteLine("\n頂點{0}到各頂點的最短路徑為:(終點 < 源點) " + g.vertex[vertex]);
63
64 //最后輸出
65 for (int i = 0; i < g.vertexNum; i++)
66 {
67 if (tempvertex[i] == 1)
68 {
69 var index = i;
70
71 while (index != vertex)
72 {
73 var j = index;
74 Console.Write("{0} < ", g.vertex[index]);
75 index = path[index];
76 }
77 Console.WriteLine("{0}\n", g.vertex[index]);
78 }
79 else
80 {
81 Console.WriteLine("{0} <- {1}: 無路徑\n", g.vertex[i], g.vertex[vertex]);
82 }
83 }
84 }
85 #endregion



最后上一下總的運行代碼

View Code
  1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace MatrixGraph
7 {
8 public class Program
9 {
10 static void Main(string[] args)
11 {
12 MatrixGraphManager manager = new MatrixGraphManager();
13
14 //創建圖
15 MatrixGraph graph = manager.CreateMatrixGraph();
16
17 manager.OutMatrix(graph);
18
19 int sum = 0;
20
21 manager.Prim(graph, out sum);
22
23 Console.WriteLine("\n最小生成樹的權值為:" + sum);
24
25 manager.Dijkstra(graph);
26
27 //Console.Write("廣度遞歸:\t");
28
29 //manager.BFSTraverse(graph);
30
31 //Console.Write("\n深度遞歸:\t");
32
33 //manager.DFSTraverse(graph);
34
35 Console.ReadLine();
36
37 }
38 }
39
40 #region 鄰接矩陣的結構圖
41 /// <summary>
42 /// 鄰接矩陣的結構圖
43 /// </summary>
44 public class MatrixGraph
45 {
46 //保存頂點信息
47 public string[] vertex;
48
49 //保存邊信息
50 public int[,] edges;
51
52 //深搜和廣搜的遍歷標志
53 public bool[] isTrav;
54
55 //頂點數量
56 public int vertexNum;
57
58 //邊數量
59 public int edgeNum;
60
61 //圖類型
62 public int graphType;
63
64 /// <summary>
65 /// 存儲容量的初始化
66 /// </summary>
67 /// <param name="vertexNum"></param>
68 /// <param name="edgeNum"></param>
69 /// <param name="graphType"></param>
70 public MatrixGraph(int vertexNum, int edgeNum, int graphType)
71 {
72 this.vertexNum = vertexNum;
73 this.edgeNum = edgeNum;
74 this.graphType = graphType;
75
76 vertex = new string[vertexNum];
77 edges = new int[vertexNum, vertexNum];
78 isTrav = new bool[vertexNum];
79 }
80
81 }
82 #endregion
83
84 /// <summary>
85 /// 圖的操作類
86 /// </summary>
87 public class MatrixGraphManager
88 {
89 #region 圖的創建
90 /// <summary>
91 /// 圖的創建
92 /// </summary>
93 /// <param name="g"></param>
94 public MatrixGraph CreateMatrixGraph()
95 {
96 Console.WriteLine("請輸入創建圖的頂點個數,邊個數,是否為無向圖(0,1來表示),已逗號隔開。");
97
98 var initData = Console.ReadLine().Split(',').Select(i => int.Parse(i)).ToList();
99
100 MatrixGraph graph = new MatrixGraph(initData[0], initData[1], initData[2]);
101
102 //我們默認“正無窮大為沒有邊”
103 for (int i = 0; i < graph.vertexNum; i++)
104 {
105 for (int j = 0; j < graph.vertexNum; j++)
106 {
107 graph.edges[i, j] = short.MaxValue;
108 }
109 }
110
111 Console.WriteLine("請輸入各頂點信息:");
112
113 for (int i = 0; i < graph.vertexNum; i++)
114 {
115 Console.Write("\n第" + (i + 1) + "個頂點為:");
116
117 var single = Console.ReadLine();
118
119 //頂點信息加入集合中
120 graph.vertex[i] = single;
121 }
122
123 Console.WriteLine("\n請輸入構成兩個頂點的邊和權值,以逗號隔開。\n");
124
125 for (int i = 0; i < graph.edgeNum; i++)
126 {
127 Console.Write("" + (i + 1) + "條邊:\t");
128
129 initData = Console.ReadLine().Split(',').Select(j => int.Parse(j)).ToList();
130
131 int start = initData[0];
132 int end = initData[1];
133 int weight = initData[2];
134
135 //給矩陣指定坐標位置賦值
136 graph.edges[start - 1, end - 1] = weight;
137
138 //如果是無向圖,則數據呈“二,四”象限對稱
139 if (graph.graphType == 1)
140 {
141 graph.edges[end - 1, start - 1] = weight;
142 }
143 }
144
145 return graph;
146 }
147 #endregion
148
149 #region 輸出矩陣數據
150 /// <summary>
151 /// 輸出矩陣數據
152 /// </summary>
153 /// <param name="graph"></param>
154 public void OutMatrix(MatrixGraph graph)
155 {
156 for (int i = 0; i < graph.vertexNum; i++)
157 {
158 for (int j = 0; j < graph.vertexNum; j++)
159 {
160 if (graph.edges[i, j] == short.MaxValue)
161 Console.Write("∽\t");
162 else
163 Console.Write(graph.edges[i, j] + "\t");
164 }
165 //換行
166 Console.WriteLine();
167 }
168 }
169 #endregion
170
171 #region 廣度優先
172 /// <summary>
173 /// 廣度優先
174 /// </summary>
175 /// <param name="graph"></param>
176 public void BFSTraverse(MatrixGraph graph)
177 {
178 //訪問標記默認初始化
179 for (int i = 0; i < graph.vertexNum; i++)
180 {
181 graph.isTrav[i] = false;
182 }
183
184 //遍歷每個頂點
185 for (int i = 0; i < graph.vertexNum; i++)
186 {
187 //廣度遍歷未訪問過的頂點
188 if (!graph.isTrav[i])
189 {
190 BFSM(ref graph, i);
191 }
192 }
193 }
194
195 /// <summary>
196 /// 廣度遍歷具體算法
197 /// </summary>
198 /// <param name="graph"></param>
199 public void BFSM(ref MatrixGraph graph, int vertex)
200 {
201 //這里就用系統的隊列
202 Queue<int> queue = new Queue<int>();
203
204 //先把頂點入隊
205 queue.Enqueue(vertex);
206
207 //標記此頂點已經被訪問
208 graph.isTrav[vertex] = true;
209
210 //輸出頂點
211 Console.Write(" ->" + graph.vertex[vertex]);
212
213 //廣度遍歷頂點的鄰接點
214 while (queue.Count != 0)
215 {
216 var temp = queue.Dequeue();
217
218 //遍歷矩陣的橫坐標
219 for (int i = 0; i < graph.vertexNum; i++)
220 {
221 if (!graph.isTrav[i] && graph.edges[temp, i] != 0)
222 {
223 graph.isTrav[i] = true;
224
225 queue.Enqueue(i);
226
227 //輸出未被訪問的頂點
228 Console.Write(" ->" + graph.vertex[i]);
229 }
230 }
231 }
232 }
233 #endregion
234
235 #region 深度優先
236 /// <summary>
237 /// 深度優先
238 /// </summary>
239 /// <param name="graph"></param>
240 public void DFSTraverse(MatrixGraph graph)
241 {
242 //訪問標記默認初始化
243 for (int i = 0; i < graph.vertexNum; i++)
244 {
245 graph.isTrav[i] = false;
246 }
247
248 //遍歷每個頂點
249 for (int i = 0; i < graph.vertexNum; i++)
250 {
251 //廣度遍歷未訪問過的頂點
252 if (!graph.isTrav[i])
253 {
254 DFSM(ref graph, i);
255 }
256 }
257 }
258
259 #region 深度遞歸的具體算法
260 /// <summary>
261 /// 深度遞歸的具體算法
262 /// </summary>
263 /// <param name="graph"></param>
264 /// <param name="vertex"></param>
265 public void DFSM(ref MatrixGraph graph, int vertex)
266 {
267 Console.Write("->" + graph.vertex[vertex]);
268
269 //標記為已訪問
270 graph.isTrav[vertex] = true;
271
272 //要遍歷的六個點
273 for (int i = 0; i < graph.vertexNum; i++)
274 {
275 if (graph.isTrav[i] == false && graph.edges[vertex, i] != 0)
276 {
277 //深度遞歸
278 DFSM(ref graph, i);
279 }
280 }
281 }
282 #endregion
283 #endregion
284
285 #region prim算法獲取最小生成樹
286 /// <summary>
287 /// prim算法獲取最小生成樹
288 /// </summary>
289 /// <param name="graph"></param>
290 public void Prim(MatrixGraph graph, out int sum)
291 {
292 //已訪問過的標志
293 int used = 0;
294
295 //非鄰接頂點標志
296 int noadj = -1;
297
298 //定義一個輸出總權值的變量
299 sum = 0;
300
301 //臨時數組,用於保存鄰接點的權值
302 int[] weight = new int[graph.vertexNum];
303
304 //臨時數組,用於保存頂點信息
305 int[] tempvertex = new int[graph.vertexNum];
306
307 //取出鄰接矩陣的第一行數據,也就是取出第一個頂點並將權和邊信息保存於臨時數據中
308 for (int i = 1; i < graph.vertexNum; i++)
309 {
310 //保存於鄰接點之間的權值
311 weight[i] = graph.edges[0, i];
312
313 //等於0則說明V1與該鄰接點沒有邊
314 if (weight[i] == short.MaxValue)
315 tempvertex[i] = noadj;
316 else
317 tempvertex[i] = int.Parse(graph.vertex[0]);
318 }
319
320 //從集合V中取出V1節點,只需要將此節點設置為已訪問過,weight為0集合
321 var index = tempvertex[0] = used;
322 var min = weight[0] = short.MaxValue;
323
324 //在V的鄰接點中找權值最小的節點
325 for (int i = 1; i < graph.vertexNum; i++)
326 {
327 index = i;
328 min = short.MaxValue;
329
330 for (int j = 1; j < graph.vertexNum; j++)
331 {
332 //用於找出當前節點的鄰接點中權值最小的未訪問點
333 if (weight[j] < min && tempvertex[j] != 0)
334 {
335 min = weight[j];
336 index = j;
337 }
338 }
339 //累加權值
340 sum += min;
341
342 Console.Write("({0},{1}) ", tempvertex[index], graph.vertex[index]);
343
344 //將取得的最小節點標識為已訪問
345 weight[index] = short.MaxValue;
346 tempvertex[index] = 0;
347
348 //從最新的節點出發,將此節點的weight比較賦值
349 for (int j = 0; j < graph.vertexNum; j++)
350 {
351 //已當前節點為出發點,重新選擇最小邊
352 if (graph.edges[index, j] < weight[j] && tempvertex[j] != used)
353 {
354 weight[j] = graph.edges[index, j];
355
356 //這里做的目的將較短的邊覆蓋點上一個節點的鄰接點中的較長的邊
357 tempvertex[j] = int.Parse(graph.vertex[index]);
358 }
359 }
360 }
361 }
362 #endregion
363
364 #region dijkstra求出最短路徑
365 /// <summary>
366 /// dijkstra求出最短路徑
367 /// </summary>
368 /// <param name="g"></param>
369 public void Dijkstra(MatrixGraph g)
370 {
371 int[] weight = new int[g.vertexNum];
372
373 int[] path = new int[g.vertexNum];
374
375 int[] tempvertex = new int[g.vertexNum];
376
377 Console.WriteLine("\n請輸入源點的編號:");
378
379 //讓用戶輸入要遍歷的起始點
380 int vertex = int.Parse(Console.ReadLine()) - 1;
381
382 for (int i = 0; i < g.vertexNum; i++)
383 {
384 //初始賦權值
385 weight[i] = g.edges[vertex, i];
386
387 if (weight[i] < short.MaxValue && weight[i] > 0)
388 path[i] = vertex;
389
390 tempvertex[i] = 0;
391 }
392
393 tempvertex[vertex] = 1;
394 weight[vertex] = 0;
395
396 for (int i = 0; i < g.vertexNum; i++)
397 {
398 int min = short.MaxValue;
399
400 int index = vertex;
401
402 for (int j = 0; j < g.vertexNum; j++)
403 {
404 //頂點的權值中找出最小的
405 if (tempvertex[j] == 0 && weight[j] < min)
406 {
407 min = weight[j];
408 index = j;
409 }
410 }
411
412 tempvertex[index] = 1;
413
414 //以當前的index作為中間點,找出最小的權值
415 for (int j = 0; j < g.vertexNum; j++)
416 {
417 if (tempvertex[j] == 0 && weight[index] + g.edges[index, j] < weight[j])
418 {
419 weight[j] = weight[index] + g.edges[index, j];
420 path[j] = index;
421 }
422 }
423 }
424
425 Console.WriteLine("\n頂點{0}到各頂點的最短路徑為:(終點 < 源點) " + g.vertex[vertex]);
426
427 //最后輸出
428 for (int i = 0; i < g.vertexNum; i++)
429 {
430 if (tempvertex[i] == 1)
431 {
432 var index = i;
433
434 while (index != vertex)
435 {
436 var j = index;
437 Console.Write("{0} < ", g.vertex[index]);
438 index = path[index];
439 }
440 Console.WriteLine("{0}\n", g.vertex[index]);
441 }
442 else
443 {
444 Console.WriteLine("{0} <- {1}: 無路徑\n", g.vertex[i], g.vertex[vertex]);
445 }
446 }
447 }
448 #endregion
449 }
450 }

 

算法速成系列至此就全部結束了,公司給我們的算法培訓也於上周五結束,呵呵,趕一下同步。最后希望大家能對算法重視起來,

學好算法,終身收益。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM