C++语言代码设计算法求解vi到vj之间的最短路径(每条边长度为1)
时间: 2023-06-18 10:02:53 浏览: 117
可以使用Dijkstra算法来求解从vi到vj之间的最短路径。以下是C++代码实现:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
vector<int> Dijkstra(vector<vector<int>>& graph, int start, int end) {
int n = graph.size();
vector<int> dist(n, INF);
vector<int> prev(n, -1);
vector<bool> visited(n, false);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
dist[start] = 0;
pq.push(make_pair(dist[start], start));
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (visited[u]) continue;
visited[u] = true;
if (u == end) break;
for (int v = 0; v < n; v++) {
if (graph[u][v] > 0 && !visited[v]) {
if (dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
prev[v] = u;
pq.push(make_pair(dist[v], v));
}
}
}
}
vector<int> path;
int curr = end;
while (curr != start) {
path.push_back(curr);
curr = prev[curr];
}
path.push_back(start);
reverse(path.begin(), path.end());
return path;
}
int main() {
int n = 7; // 7个节点
vector<vector<int>> graph(n, vector<int>(n, 0)); // 初始化图
graph[0][1] = graph[1][0] = 1;
graph[0][2] = graph[2][0] = 1;
graph[1][3] = graph[3][1] = 1;
graph[1][4] = graph[4][1] = 1;
graph[2][4] = graph[4][2] = 1;
graph[3][5] = graph[5][3] = 1;
graph[4][5] = graph[5][4] = 1;
graph[4][6] = graph[6][4] = 1;
int start = 0; // 起点
int end = 6; // 终点
vector<int> path = Dijkstra(graph, start, end);
cout << "最短路径为: ";
for (int i = 0; i < path.size(); i++) {
cout << path[i] << " ";
}
cout << endl;
return 0;
}
```
这段代码中,我们首先定义了一个7个节点的图,并初始化了每条边的长度为1。接着,我们调用了Dijkstra算法,并传入起点和终点作为参数。算法返回的是一个从起点到终点的最短路径,我们将其输出即可。
阅读全文