编程语言
首页 > 编程语言> > [C] Dijkstra算法——通过边实现松弛

[C] Dijkstra算法——通过边实现松弛

作者:互联网

Dijkstra算法——通过边实现松弛


代码实现

#include<stdio.h>
int a[2000][2000];
int inf = 99999999;
int dis[2000], book[2000];
int main()
{
    int i, j, k, m, n, x, y, s, u, v;
    int min;
    scanf("%d %d", &n, &m);
    /* */
    //初始化
    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++)
            if (i == j)
                a[i][j] = 0;
            else
                a[i][j] = inf;

    //读入边(有向图)
    for (i = 1; i <= m; i++)
    {
        scanf("%d %d %d", &x, &y, &s);
        a[x][y] = s;
    }

    for (i = 1; i <= n; i++)
        dis[i] = a[1][i];
    for (i = 1; i <= n; i++)
        book[i] = 0;
    book[1] = 1;

    //Dijkstra 算法核心语句
    for (i = 1; i <= n; i++)
    {
        //找到离1号顶点最近的点
        min = inf;
        for (j = 1; j <= n; j++)
        {
            if (book[j] == 0 && dis[j] < min)
            {
                min = dis[j];
                u = j;
            }
        }
        book[u] = 1;
        for (v = 1; v <= n; v++)
        {
            if (a[u][v] < inf)
            {
                if (dis[v] > dis[u] + a[u][v])
                {
                    dis[v] = dis[u] + a[u][v];
                }
            }
        }
    }
    for (i = 1; i <= n; i++)
    {
        printf("%d ", dis[i]);
    }
    return 0;
}

运行结果:
在这里插入图片描述

标签:松弛,int,算法,Warshall,Dijkstra,Floyd,顶点,dis
来源: https://blog.csdn.net/qq_36286039/article/details/120284992