最短路(Dijkstra算法)

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int maps[10][10], dis[10], book[10], i, j, n, m, t1, t2, t3, u, v, mins;
    int inf = INT_MAX;
    scanf("%d %d", &n, &m);
    for(i = 1; i <= n; i++)
        {
            for(j = 1; j <= n; j++)
                    maps[i][j] = inf;
            maps[i][i] = 0;
        }
    for(i = 1; i <= m; i++)
        {
            scanf("%d %d %d", &t1, &t2, &t3);
            maps[t1][t2] = t3;
        }
    for(i = 1; i <= n; i++)
        dis[i] = maps[1][i];
    for(i = 1; i <= n; i++)
        book[i] = 0;
    book[1] = 1;
//算法核心语句
 for(i = 1; i < n; i++)
        {
            mins = inf;
            for(j = 1; j <= n; j++)
                {
                    if(book[j] == 0 && dis[j] < mins)
                        {
                            mins = dis[j];
                            u = j;
                        }
                }
            book[u] = 1;
            for(v = 1; v <= n; v++)
                {
                    if(maps[u][v] < inf)
                        dis[v] = min(dis[v], maps[u][v] + dis[u]);   //对出边松弛
                }
        }
    for(i = 1; i <= n; i++)
        printf("%d ", dis[i]);
    getchar();
    return 0;
}

    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/sduthao/article/details/76175576
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞