设置结构体
enum NodeName { A, B, C, D, E, F, G, H, I, J };
const int MAX_NUM_NODES = 10;
const int INF = numeric_limits<int>::max();
定义一个节点类
class Node {
public:
Node(NodeName name) : name_(name), distance_(INF) {}
NodeName get_name() const { return name_; }
void set_distance(int distance) { distance_ = distance; }
int get_distance() const { return distance_; }
void add_neighbor(const Node& node, int weight) { neighbors_[node.get_name()] = weight; }
const map<NodeName, int>& get_neighbors() const { return neighbors_; }
private:
NodeName name_;
map<NodeName, int> neighbors_;
int distance_;
};
采用Dijkstra算法求最短路径
void Dijkstra(const vector<Node>& graph, NodeName start, NodeName end, vector<NodeName>& shortest_path) {
// 定义已处理节点集合和未处理节点集合
map<NodeName, bool> processed;
map<NodeName, bool> unprocessed;
// 定义每个节点的最短路
map<NodeName, int> shortest_distances;
// 初始化未处理节点集合和最短路
for (int i = 0; i < graph.size(); ++i) {
NodeName name = static_cast<NodeName>(i);
unprocessed[name] = true;
shortest_distances[name] = INF;
}
shortest_distances[start] = 0; // 起点的最短路为0
NodeName current = start;
// 进行Dijkstra算法的核心部分
while (current != end) {
// 从当前节点开始遍历其所有邻居节点,更新其邻居节点的最短路
for (const auto& neighbor : graph[current].get_neighbors()) {
int new_distance = shortest_distances[current] + neighbor.second;
if (new_distance < shortest_distances[neighbor.first]) {
shortest_distances[neighbor.first] = new_distance;
}
}
// 标记当前节点为已处理节点,并从未处理节点集合中移除
processed[current] = true;
unprocessed.erase(current);
// 从未处理节点中找到距离起点最近的节点
int shortest_distance = INF;
for (const auto& node : unprocessed) {
if (shortest_distances[node.first] < shortest_distance) {
current = node.first;
shortest_distance = shortest_distances[node.first];
}
}
if (shortest_distance == INF) {
// 如果当前节点也没能够更新邻居节点的最短路距离,则无法到达终点
break;
}
}
// 构造最短路的节点序列
shortest_path.clear();
shortest_path.push_back(end);
NodeName node = end;
while (node != start) {
for (const auto& neighbor : graph[node].get_neighbors()) {
if (shortest_distances[node] == shortest_distances[neighbor.first] + neighbor.second) {
node = neighbor.first;
shortest_path.push_back(node);
break;
}
}
}
reverse(shortest_path.begin(), shortest_path.end()); // 反转最短路节点序列,使之成为从起点到终点的顺序
}