朴素Dijkstra求最短路

迪杰斯特拉算法(Dijkstra)是由荷兰计算机科学家狄克斯特拉于1959 年提出的,因此又叫狄克斯特拉算法。是从一个顶点到其余各顶点的最短路径算法,解决的是有权图中最短路径问题。迪杰斯特拉算法主要特点是从起始点开始,采用贪心算法的策略,每次遍历到始点距离最近且未访问过的顶点的邻接节点,直到扩展到终点为止。

朴素Dijkstra适用于求稠密图,时间复杂度n * n,用邻接矩阵求存储。

思想:看的我们数据结构老师的ppt看懂的
在这里插入图片描述
在这里插入图片描述

例如从起点1到其他点的最短距离
在这里插入图片描述

代码模板

int Dijkstra(){
    
    
    
    memset(dist,0x3f,sizeof dist);   //初始化距离 注意这行是把dist[i]初始化为0x3f3f3f3f了而不是0x3f3f
    dist[1] = 0;   //如果要是求第i个点到其他点的距离,就dist[i] = 0;
    
    for(int i = 1; i <= n; i++){
    
        //n次迭代,每次求出离起点最短的距离,并把该点加到s集合中,然后更新其他点
        
        int t = -1;
        for(int j = 1; j<=n; j++)
            if(!st[j] && (dist[j] < dist[t] || t == -1))   //找到不在集合中且距离最近的点
                t = j;
            

        for(int j = 1;j <= n;j++)
            dist[j] = min(dist[j],dist[t] + g[t][j]);   //更新其他点
        
        st[t] = true;    
    }
    
    if(dist[n] == 0x3f3f3f3f)
        return -1;
    return dist[n];
}

没有注释的代码

int Dijkstra(){
    
    
    
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    for(int i = 1;i <= n;i++){
    
    
        
        int t = -1;
        for(int j = 1;j <= n;j++)
            if(!st[j] && (t == -1 || dist[j] < dist[t]))
                t = j;
        for(int j = 1;j<=n;j++)
            dist[j] = min(dist[j],dist[t] + g[t][j]);
            
        st[t] = true;
            
    }
    
    if(dist[n] == 0x3f3f3f3f)
        return -1;
    return dist[n];
}

例题

Dijkstra求最短路 I

给定一个n个点m条边的有向图,图中可能存在重边和自环,所有边权均为正值。

请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出-1。
输入格式

第一行包含整数n和m。

接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式

输出一个整数,表示1号点到n号点的最短距离。

如果路径不存在,则输出-1。
数据范围

1≤n≤50,
1≤m≤10^5,
图中涉及边长均不超过10000。
输入样例:

3 3
1 2 2
2 3 1
1 3 4

输出样例:

3

代码

#include <iostream>
#include <cstring>
using namespace std;

const int N = 510;

int g[N][N];
int dist[N];
bool st[N];

int n, m;
int x ,y ,z;

int Dijkstra();

int main(){
    
    
    
    
    cin>>n>>m;
    
    memset(g,0x3f,sizeof g);   //题目说存在重边,所以我们要存最小的那条边,这里初始化为无穷大
    
    while(m--){
    
    
        cin>>x>>y>>z;
        g[x][y] = min(z,g[x][y]);
        
    }
    
    cout<<Dijkstra()<<endl;
    
    return 0;

}

int Dijkstra(){
    
    
    
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    for(int i = 1;i <= n;i++){
    
    
        
        int t = -1;
        for(int j = 1;j <= n;j++)
            if(!st[j] && (t == -1 || dist[j] < dist[t]))
                t = j;
        for(int j = 1;j<=n;j++)
            dist[j] = min(dist[j],dist[t] + g[t][j]);
            
        st[t] = true;
            
    }
    
    if(dist[n] == 0x3f3f3f3f)
        return -1;
    return dist[n];
}

猜你喜欢

转载自blog.csdn.net/fjd7474/article/details/109571580