用C++编写一个迪杰斯特拉算法的代码
时间: 2023-09-02 12:07:45 浏览: 80
迪杰斯特拉算法C++实现
好的,下面是一个简单的迪杰斯特拉算法的C++代码实现:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
typedef pair<int, int> pii; //pair<int, int>表示一个节点和其到起点的距离
void dijkstra(vector<vector<pii>>& graph, int start, vector<int>& distance) {
priority_queue<pii, vector<pii>, greater<pii>> pq; //小根堆,用于按距离从小到大获取下一个最优节点
distance[start] = 0; //起点到起点的距离为0
pq.push({0, start}); //加入起点到小根堆
while (!pq.empty()) {
int curr = pq.top().second; //获取下一个最优节点
pq.pop();
for (auto neighbor : graph[curr]) { //遍历当前节点的所有邻居节点
int next = neighbor.first;
int weight = neighbor.second;
if (distance[curr] + weight < distance[next]) { //如果从起点到当前节点的距离+当前节点到邻居节点的距离<起点到邻居节点的距离,就更新邻居节点的距离
distance[next] = distance[curr] + weight;
pq.push({distance[next], next}); //将邻居节点加入小根堆
}
}
}
}
int main() {
int n = 6; //节点数
int start = 0; //起点
int end = 5; //终点
vector<vector<pii>> graph(n); //邻接表表示图
vector<int> distance(n, INT_MAX); //用于存储起点到各节点的距离,初始值为无穷大
//构建图
graph[0].push_back({1, 7});
graph[0].push_back({2, 9});
graph[0].push_back({5, 14});
graph[1].push_back({0, 7});
graph[1].push_back({2, 10});
graph[1].push_back({3, 15});
graph[2].push_back({0, 9});
graph[2].push_back({1, 10});
graph[2].push_back({3, 11});
graph[2].push_back({5, 2});
graph[3].push_back({1, 15});
graph[3].push_back({2, 11});
graph[3].push_back({4, 6});
graph[4].push_back({3, 6});
graph[4].push_back({5, 9});
graph[5].push_back({0, 14});
graph[5].push_back({2, 2});
graph[5].push_back({4, 9});
dijkstra(graph, start, distance); //求解起点到各节点的最短路径
cout << "从起点" << start << "到终点" << end << "的最短距离为:" << distance[end] << endl; //输出起点到终点的最短距离
return 0;
}
```
上面的代码实现了一个简单的迪杰斯特拉算法,可以求解起点到图中其他节点的最短路径。
阅读全文