C++ dijkstra
时间: 2023-08-30 09:11:58 浏览: 104
Dijkstra算法是一种用于求解最短路径的算法。下面是一个C++实现的完整代码示例:
```
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510;
int g[N][N];
int dis[N];
bool st[N];
int n, m;
int dijkstra(){
memset(dis, 0x3f, sizeof(dis));
dis = 0;
for(int i = 0; i < n-1; i++){
int t = -1;
for(int j = 1; j <= n; j++){
if(!st[j && (t == -1 || dis[t > dis[j]))
t = j;
}
for(int j = 1; j <= n; j++){
dis[j = min(dis[j], dis[t + g[t][j]);
}
st[t = true;
}
if(dis[n == 0x3f3f3f3f)
return -1;
return dis[n];
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
cin >> n >> m;
memset(g, 0x3f, sizeof(g));
while(m--){
int x, y, z;
cin >> x >> y >> z;
g[x][y = min(g[x][y], z);
}
cout << dijkstra() << endl;
return 0;
}
```
这段代码实现了稠密型的Dijkstra算法,通过邻接矩阵存储图。首先,我们输入图的节点个数n和边的个数m。然后,我们使用`memset`函数将邻接矩阵g的所有元素初始化为无穷大。接下来,我们通过循环输入每条边的起点、终点和权值,并将其存储在邻接矩阵g中。最后,我们调用`dijkstra`函数计算从起点到终点的最短路径,并输出结果。
请注意,这段代码是用C++语言编写的。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [dijkstra算法C++](https://blog.csdn.net/m0_72400354/article/details/127731445)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [C++实现Dijkstra算法](https://download.csdn.net/download/weixin_38615397/12724832)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文