dijkstra算法求单源最短路径长度并输出最短路径 代码

代码

/*
6 8 0
0 1 1
0 3 4
0 4 4
1 3 2
2 5 1
3 2 2
3 4 3
4 5 3
*/

#include<iostream>
#include<algorithm>

using namespace std;
const int maxv = 1000;
const int INF = 1000000000;

int n, m, s;
int G[maxv][maxv];
int d[maxv];
bool vis[maxv] = {false};
int pre[maxv];

void dijistra(int s)
{
    fill(d, d+maxv, INF);
    d[s] = 0;

    for(int i = 0; i < n; i++)
    {
        int u = -1, MIN = INF;

        for(int j = 0; j < n; j++)
        {
            if(vis[j] == false && d[j] < MIN)
            {
                u = j;
                MIN = d[j];
            }
        }

        if(u == -1) return;

        vis[u] = true;
        for(int v = 0; v < n; v++)
        {
            if(vis[v] == false && G[u][v] != INF && d[u] + G[u][v] < d[v])
            {
                d[v] = G[u][v] + d[u];
                pre[v] = u;
            }
        }

    }

}

void dfs(int s, int v)
{
    if(v == s)
    {
        printf("%d ", s);
        return;
    }
    dfs(s, pre[v]);
    printf("%d ", v);
}

int main()
{
    int u, v, w;
    scanf("%d %d %d",&n, &m, &s);

    fill(G[0], G[0]+maxv*maxv, INF);
    for(int i = 0; i < m; i++)
    {
        scanf("%d%d%d",&u, &v, &w);
        G[u][v] = w;
    }

    dijistra(s);

    for(int i = 0; i < n; i++)
    {
        printf("%d ",d[i]);
    }

    cout << endl;
    
    //输出最短路径
    for(int i = 0; i < n; i++)
    {
        dfs(0, i);
        cout << endl;
    }

    return 0;
}

具体过程以后再补

 

运行测例:

6 8 0
0 1 1
0 3 4
0 4 4
1 3 2
2 5 1
3 2 2
3 4 3
4 5 3

输出结果:

0 1 5 3 4 6
0
0 1
0 1 3 2
0 1 3
0 4
0 1 3 2 5

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页