增加查询任意两个建筑的最短路径以及所有路径
时间: 2023-11-26 13:06:45 浏览: 30
好的,我们可以使用Dijkstra算法来实现任意两个建筑的最短路径查询,使用深度优先遍历来实现所有路径查询。以下是更新后的代码:
```c++
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<stack>
using namespace std;
//图的节点类
class Node {
public:
string name; //建筑物名称
int id; //节点编号
vector<Node*> neighbors; //相邻节点
vector<int> weights; //相邻节点的权重
Node(string name, int id) {
this->name = name;
this->id = id;
}
};
//图类
class Graph {
public:
vector<Node*> nodes; //所有节点
void addNode(string name, int id) {
nodes.push_back(new Node(name, id));
}
void addEdge(int from, int to, int weight) {
nodes[from]->neighbors.push_back(nodes[to]);
nodes[from]->weights.push_back(weight);
nodes[to]->neighbors.push_back(nodes[from]);
nodes[to]->weights.push_back(weight);
}
};
//Dijkstra算法
void Dijkstra(Node* start, Node* end) {
map<Node*, int> dist; //最短距离
map<Node*, Node*> visited; //记录已访问节点的路径
priority_queue<pair<int, Node*>, vector<pair<int, Node*>>, greater<pair<int, Node*>>> pq; //最小堆
for (Node* node : start->neighbors) {
int weight = start->weights[node->id];
dist[node] = weight;
pq.push(make_pair(weight, node));
visited[node] = start;
}
while (!pq.empty()) {
Node* cur = pq.top().second;
int curDist = pq.top().first;
pq.pop();
if (cur == end) {
//输出路径
stack<Node*> path;
while (cur) {
path.push(cur);
cur = visited[cur];
}
while (!path.empty()) {
cout << path.top()->name << " ";
path.pop();
}
cout << endl;
cout << "Distance: " << curDist << endl;
return;
}
for (int i = 0; i < cur->neighbors.size(); i++) {
Node* next = cur->neighbors[i];
int weight = cur->weights[i];
if (!dist.count(next) || curDist + weight < dist[next]) {
dist[next] = curDist + weight;
pq.push(make_pair(dist[next], next));
visited[next] = cur;
}
}
}
cout << "No path found!" << endl;
}
//深度优先遍历
void DFS(Node* start, Node* end, vector<Node*>& path, vector<vector<Node*>>& paths) {
if (start == end) {
path.push_back(end);
paths.push_back(path);
path.pop_back();
return;
}
path.push_back(start);
for (Node* next : start->neighbors) {
if (find(path.begin(), path.end(), next) == path.end()) {
DFS(next, end, path, paths);
}
}
path.pop_back();
}
//所有路径查询
void findAllPaths(Node* start, Node* end) {
vector<Node*> path;
vector<vector<Node*>> paths;
DFS(start, end, path, paths);
if (paths.empty()) {
cout << "No path found!" << endl;
return;
}
cout << "All paths:" << endl;
for (vector<Node*> p : paths) {
for (Node* node : p) {
cout << node->name << " ";
}
cout << endl;
}
}
int main() {
//初始化图
Graph g;
g.addNode("教学楼", 0);
g.addNode("图书馆", 1);
g.addNode("食堂", 2);
g.addNode("体育馆", 3);
g.addEdge(0, 1, 2);
g.addEdge(0, 2, 3);
g.addEdge(1, 3, 4);
g.addEdge(2, 3, 1);
//最短路径查询
Node* start = g.nodes[0];
Node* end = g.nodes[3];
Dijkstra(start, end);
//所有路径查询
findAllPaths(start, end);
return 0;
}
```
在上述代码中,我们增加了节点之间的权重信息,并使用Dijkstra算法来实现任意两个建筑的最短路径查询。同时,我们使用深度优先遍历来实现所有路径查询。在主函数中,我们创建了一个简单的校园图,并分别进行了最短路径查询和所有路径查询。