您好,登錄后才能下訂單哦!
C++算法庫中最常用的最短路徑算法是Dijkstra算法和Floyd-Warshall算法。
C++標準庫中提供了std::priority_queue和std::vector等數據結構來實現Dijkstra算法。以下是Dijkstra算法的偽代碼:
void Dijkstra(Graph graph, int source) {
int n = graph.size();
vector<int> dist(n, INT_MAX);
dist[source] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, source});
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (auto& edge : graph[u]) {
int v = edge.first;
int weight = edge.second;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}
}
C++標準庫中提供了std::vector等數據結構來實現Floyd-Warshall算法。以下是Floyd-Warshall算法的偽代碼:
void FloydWarshall(Graph graph) {
int n = graph.size();
vector<vector<int>> dist(n, vector<int>(n, INT_MAX));
for (int i = 0; i < n; ++i) {
dist[i][i] = 0;
for (auto& edge : graph[i]) {
int j = edge.first;
int weight = edge.second;
dist[i][j] = weight;
}
}
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
這兩種算法都能有效地求解最短路徑問題,具體選擇哪一種算法取決于具體的應用場景和需求。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。