dijkstra算法

Dijkstra算法是一种用于在带权图中找到单个源点到所有其他点的最短路径的算法。它属于贪心算法的一种,适用于有非负权重的图。在C++中实现Dijkstra算法通常使用优先队列(如C++ STL中的std::priority_queue)来优化性能,因为它可以保证每次选取当前最短路径的顶点。

以下是一个使用C++实现的Dijkstra算法的示例代码:

#include <iostream>
#include <vector>
#include <queue>
#include <climits>  // 用于INT_MAX
 
using namespace std;
 
// 定义边的结构体
struct Edge {
    int to;  // 边的终点
    int cost;  // 边的权重
};
 
// 定义优先队列中的元素,用于存储顶点和到起点的距离
struct Node {
    int vertex;  // 顶点编号
    int distance;  // 从源点到该顶点的距离
    bool operator>(const Node& that) const {
        return this->distance > that.distance;  // 大顶堆转换为小顶堆
    }
};
 
// Dijkstra算法实现
void dijkstra(const vector<vector<Edge>>& graph, int src, vector<int>& distances) {
    int n = graph.size();
    distances.assign(n, INT_MAX);  // 初始化距离数组为无穷大
    distances[src] = 0;  // 源点到自身的距离为0
    priority_queue<Node, vector<Node>, greater<Node>> pq;  // 小顶堆优化
    pq.push({src, 0});  // 将源点加入优先队列,距离为0
 
    while (!pq.empty()) {
        Node current = pq.top();  // 获取当前最小距离的顶点
        pq.pop();
        int u = current.vertex;
        int d = current.distance;
 
        // 如果当前距离大于已记录的距离,则跳过该顶点
        if (d > distances[u]) continue;
 
        // 遍历当前顶点的所有邻接边
        for (const Edge& edge : graph[u]) {
            if (distances[edge.to] > d + edge.cost) {  // 发现更短的路径
                distances[edge.to] = d + edge.cost;  // 更新距离
                pq.push({edge.to, distances[edge.to]});  // 将新顶点加入优先队列
            }
        }
    }
}
 
int main() {
    int n = 5;  // 顶点数
    vector<vector<Edge>> graph(n);  // 邻接表表示的图
    // 添加边和权重,例如:从顶点0到顶点1的权重为10,从顶点0到顶点2的权重为5等。
    graph[0] = {{1, 10}, {2, 5}};
    graph[1] = {{3, 1}, {2, 3}};
    graph[2] = {{3, 2}, {4, 1}};
    graph[3] = {{4, 4}};
    graph[4] = {}; // 注意最后一个顶点的邻接表为空,因为没有出边。
    vector<int> distances; // 存储从源点到所有其他顶点的最短距离
    dijkstra(graph, 0, distances); // 从顶点0开始计算最短路径,结果存储在distances中。
    for (int i = 0; i < n; ++i) {
        cout << "Distance of vertex " << i << " from source is " << distances[i] << endl;
    }
    return 0;
}

这段代码首先定义了一个图的邻接表表示,然后实现了Dijkstra算法。使用优先队列(小顶堆)来优化选择最短路径的顶点的过程。最后,主函数中构建了一个图,并调用dijkstra函数计算从顶点0到所有其他顶点的最短路径,并打印结果。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值