C++语言实现最短路径算法(Shortest Path)在C++中实现最短路径算法,可以使用Dijkstra算法。以下是一个使用Dijkstra算法来计算图中单源最短路径的示例:
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
#include <limits>
using namespace std;
typedef pair<int, int> Edge; // (weight, vertex)
class Graph {
int vertices;
vector<vector<Edge>> adjacencyList;
public:
Graph(int v) : vertices(v), adjacencyList(v) {}
void addEdge(int source, int target, int weight) {
adjacencyList[source].emplace_back(weight, target);
adjacencyList[target].emplace_back(weight, source); // 如果是有向图,则去掉这一行
}
void dijkstra(int startVertex) {
vector<int> distances(vertices, numeric_limits<int>::max());
distances[startVertex] = 0;
priority_queue<Edge, vector<Edge>, greater<Edge>> pq;
pq.emplace(0, startVertex);
while (!pq.empty()) {
int currentDistance = pq.top().first;
int currentVertex = pq.top().second;
pq.pop();
for (const auto& neighbor : adjacencyList[currentVertex]) {
int weight = neighbor.first;
int target = neighbor.second;
int distance = currentDistance + weight;
if (distance < distances[target]) {
distances[target] = distance;
pq.emplace(distance, target);
}
}
}
printShortestPaths(startVertex, distances);
}
void printShortestPaths(int startVertex, const vector<int>& distances) {
cout << "Vertex\tDistance from Source " << startVertex << endl;
for (int i = 0; i < vertices; ++i) {
cout << i << "\t\t" << distances[i] << endl;
}
}
};
int main() {
int vertices = 6;
Graph graph(vertices);
graph.addEdge(0, 1, 4);
graph.addEdge(0, 2, 3);
graph.addEdge(1, 2, 1);
graph.addEdge(1, 3, 2);
graph.addEdge(2, 3, 4);
graph.addEdge(3, 4, 2);
graph.addEdge(4, 5, 6);
graph.dijkstra(0);
return 0;
}
在这个示例中,我们创建了一个包含6个顶点的图,并添加了一些边。然后,我们从顶点0开始运行Dijkstra算法,计算并打印出从顶点0到所有其他顶点的最短路径距离。代码使用了C++标准库中的priority_queue
来实现优先队列,以确保每次都选择距离最短的顶点进行处理。