Dijkstra C++模板

本文详细介绍了一种用于寻找图中两点间最短路径的经典算法——Dijkstra算法,并提供了完整的C++实现代码示例。该算法通过迭代的方式更新从起始点到各顶点的距离,最终求得最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 /*******************************************************************************
2 * Name: Dijkstra Function
3 * Description : Find the shortest path from the start point to all other points
4 * Parameter list: edge - adjacency matrix of the graph
5 * dist - array of the shortest distance from start point
6 * path - array of the shortest path
7 * order - the number of the vertex
8 * start - start point
9 * maxNum - max distance means there is no path
10 ********************************************************************************/
11  void dijkstra(int *edge, int *dist, int *path, const int order ,int start, const int maxNum)
12 {
13 bool *visited = new bool[order];
14
15 memset(visited, 0, sizeof(bool) * order);
16 memset(dist, 0, sizeof(int) * order);
17 for (int i = 0; i < order; i++)
18 {
19 path[i] = -1;
20 dist[i] = maxNum;
21 }
22
23 visited[start] = true;
24 dist[start] = 0;
25
26 int curs = start;
27 int minDist, tempDist, tempCurs;
28
29 for (int i = 1; i < order; i++)
30 {
31 minDist = maxNum;
32 for (int j = 0; j < order; j++)
33 {
34 if(!visited[j])
35 {
36 tempDist = dist[curs] + *(edge + curs * order + j);
37 if ( tempDist < dist[j])
38 {
39 dist[j] = tempDist;
40 path[j] = curs;
41 }
42 if(minDist > dist[j])
43 {
44 minDist = dist[j];
45 tempCurs = j;
46 }
47 }
48 }
49 curs = tempCurs;
50 visited[curs] = true;
51 }
52 delete []visited;
53 }
调用示例:

1 const int maxNum = 1e8;
2 int a[5][5] = {{0, 10, maxNum, 30, 100},{maxNum, 0, 50, maxNum, maxNum},
3 {maxNum, maxNum, 0, maxNum, 10}, {maxNum, maxNum, 20, 0, 60}, {maxNum, maxNum, maxNum, maxNum, 0}};
4 int b[5];
5 int d[5];
6 dijkstra((int *)a, d, b, 5, 0, maxNum);

 

转载于:https://www.cnblogs.com/ltang/archive/2010/11/02/1866863.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值