可以实现自己输入数据,和任意两个顶点
时间: 2024-03-21 07:38:59 浏览: 19
当然可以,以下是可以自己输入数据,任意选择起点和终点的C++代码实现。
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f; // 无穷大
int dijkstra(vector<vector<int>> &graph, int s, int t, int n) {
vector<int> dist(n, INF); // 存储到起点的最短距离
vector<bool> vis(n, false); // 标记节点是否已确定最短路径
dist[s] = 0; // 起点到自身的距离为0
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // 存储距离起点最近的节点
pq.push(make_pair(0, s)); // 将起点加入队列
while(!pq.empty()) {
int u = pq.top().second; // 取出距离起点最近的节点
pq.pop();
if(vis[u]) continue; // 如果该节点已确定最短路径,则跳过
vis[u] = true; // 标记该节点已确定最短路径
for(int v = 0; v < n; v++) {
if(graph[u][v] > 0 && !vis[v]) { // 如果u和v之间有边,并且v未确定最短路径
if(dist[u] + graph[u][v] < dist[v]) { // 如果从起点到v的距离比原来的更短
dist[v] = dist[u] + graph[u][v]; // 更新v的距离
pq.push(make_pair(dist[v], v)); // 将v加入队列
}
}
}
}
return dist[t]; // 返回起点到终点的最短距离
}
int main() {
int n; // 节点个数
int s, t; // 起点和终点
// 输入节点个数
cout << "Enter the number of nodes: ";
cin >> n;
// 输入边权重
vector<vector<int>> graph(n, vector<int>(n, 0));
cout << "Enter the edge weight matrix:" << endl;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cin >> graph[i][j];
}
}
// 输入起点和终点
cout << "Enter the source node: ";
cin >> s;
cout << "Enter the target node: ";
cin >> t;
int dist = dijkstra(graph, s, t, n);
cout << "Shortest distance from node " << s << " to node " << t << " is " << dist << endl;
return 0;
}
```
在这个程序中,我们首先询问用户有多少个节点,然后要求用户输入边权重。接下来,我们询问起点和终点,然后使用Dijkstra算法计算这两个节点之间的最短路径。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)