dijkstra算法c++代码实现
时间: 2024-04-10 08:25:19 浏览: 130
Dijkstra算法是一种用于解决单源最短路径问题的经典算法。下面是Dijkstra算法的C++代码实现:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
// 定义图的邻接表表示
typedef pair<int, int> pii;
typedef vector<vector<pii>> Graph;
// Dijkstra算法实现
vector<int> dijkstra(const Graph& graph, int start) {
int n = graph.size();
vector<int> dist(n, INT_MAX); // 存储起点到各个顶点的最短距离
vector<bool> visited(n, false); // 记录顶点是否已访问
priority_queue<pii, vector<pii>, greater<pii>> pq; // 小顶堆,存储顶点和距离的pair
dist[start] = 0; // 起点到自身的距离为0
pq.push(make_pair(0, start));
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (visited[u]) {
continue;
}
visited[u] = true;
for (const auto& neighbor : graph[u]) {
int v = neighbor.first;
int weight = neighbor.second;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push(make_pair(dist[v], v));
}
}
}
return dist;
}
int main() {
int n, m; // n为顶点数,m为边数
cin >> n >> m;
Graph graph(n);
for (int i = 0; i < m; ++i) {
int u, v, weight;
cin >> u >> v >> weight;
graph[u].push_back(make_pair(v, weight));
graph[v].push_back(make_pair(u, weight));
}
int start;
cin >> start;
vector<int> shortestDist = dijkstra(graph, start);
for (int i = 0; i < n; ++i) {
cout << "Shortest distance from " << start << " to " << i << " is " << shortestDist[i] << endl;
}
return 0;
}
```
阅读全文