#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
// 定义边的结构体,包含目标节点和边的权重
struct Edge {
int to; // 目标节点
int weight; // 边的权重
Edge(int t, int w) : to(t), weight(w) {}
};
// 定义优先队列中的节点结构体
struct Node {
int id; // 节点ID
int dist; // 从起点到该节点的距离
Node(int i, int d) : id(i), dist(d) {}
// 重载>运算符,用于优先队列(最小堆)
bool operator>(const Node& other) const {
return dist > other.dist;
}
};
/**
* Dijkstra算法实现
* @param graph: 邻接表表示的图
* @param start: 起点节点
* @param n: 节点总数
* @return: 返回从起点到所有节点的最短距离向量
*/
vector<int> dijkstra(const vector<vector<Edge>>& graph, int start, int n) {
// 初始化距离数组,所有节点初始距离为无穷大
vector<int> dist(n, INT_MAX);
// 标记节点是否已访问
vector<bool> visited(n, false);
// 使用优先队列(最小堆)来选择当前距离最小的节点
priority_queue<Node, vector<Node>, greater<Node>> pq;
// 起点到自身的距离为0
dist[start] = 0;
pq.push(Node(start, 0));
while (!pq.empty()) {
// 取出当前距离最小的节点
Node current = pq.top();
pq.pop();
int u = current.id;
// 如果该节点已经访问过,跳过
if (visited[u]) continue;
// 标记节点为已访问
visited[u] = true;
// 遍历当前节点的所有邻接边
for (const Edge& edge : graph[u]) {
int v = edge.to;
int weight = edge.weight;
// 如果通过当前节点u到达v的距离更短,则更新距离
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
// 将更新后的节点加入优先队列
pq.push(Node(v, dist[v]));
}
}
}
return dist;
}
// 示例使用函数
int main() {
// 示例:5个节点的图
int n = 5;
vector<vector<Edge>> graph(n);
// 构建图的邻接表
// 节点0的边
graph[0].push_back(Edge(1, 4));
graph[0].push_back(Edge(2, 1));
// 节点1的边
graph[1].push_back(Edge(3, 1));
// 节点2的边
graph[2].push_back(Edge(1, 2));
graph[2].push_back(Edge(3, 5));
// 节点3的边
graph[3].push_back(Edge(4, 3));
// 从节点0开始执行Dijkstra算法
int start = 0;
vector<int> distances = dijkstra(graph, start, n);
// 输出结果
cout << "从节点 " << start << " 到各节点的最短距离:" << endl;
for (int i = 0; i < n; i++) {
if (distances[i] == INT_MAX) {
cout << "节点 " << i << ": 不可达" << endl;
} else {
cout << "节点 " << i << ": " << distances[i] << endl;
}
}
return 0;
}
<code_end>
该Dijkstra算法模板具有以下特点:
1. 使用邻接表存储图结构,支持稀疏图的高效处理
2. 采用优先队列优化,时间复杂度为O((V+E)logV)
3. 包含完整的错误处理,处理不可达节点情况
4. 代码结构清晰,注释详细,便于理解和修改
5. 提供完整的示例使用代码,可直接运行测试最短路
这是 2025年10月27日 存档的第 1 版,不是当前版本。查看当前版本