版本比较
最短路
正文
增加 16 行删除 16 行
16 行未改动1718192021212223242510 行未改动36373839404041424343444546474748495051525353545556565758595960616263646465666768697071727373747576777879808182828384858687878889909091929394949596979798991001011011021031041051061071081091101111111121131141156 行未改动16 行未改动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; }10 行未改动 // 初始化距离数组,所有节点初始距离为无穷大 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算法模板具有以下特点:6 行未改动