C语言实现dijkstra(adjacence matrix)

单源最短路径算法dijkstra算法的c语言实现。算法详解请查看:

这个实现使用的图使用邻接矩阵(adjacence matirx)表示的.

#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
// Number of vertices in the graph
#define V 9

// a utility function to find the vertex with minmum distance value
int minDistance(int dist[],bool sptSet[])
{
    int min=INT_MAX;
    int min_index;
    for(int i=0;i<V;i++)
    {
        if(sptSet[i]==false && dist[i]<min)
        {
            min=dist[i];
            min_index=i;
        }
    }
    return min_index;
}

// a utility function to print solution
void printSolution(int dist[],int src)
{
    printf("vertex      distance from source %d\n",src);
    for(int i=0;i<V;i++)
    {
        printf("%d \t\t%d\n",i,dist[i]);
    }
}

void dijkstra(int graph[V][V],int src)
{
    int dist[V];
    bool sptSet[V];

    // initialize dist and sptSet
    for(int i=0;i<V;i++)
    {
        dist[i]=INT_MAX;
        sptSet[i]=false;
    }
    dist[src]=0;

    // find shortest path for all vertex
    for(int count=0;count<V-1;count++)
    {
        int u=minDistance(dist,sptSet);
        sptSet[u]=true;
        for(int v=0;v<V;v++)
        {
            if(sptSet[v]==false && graph[u][v] && dist[u]+graph[u][v]<dist[v])
                dist[v]=dist[u]+graph[u][v];
        }
    }

    printSolution(dist,src);
}

int main(void)
{
    int graph[V][V]={
         {0, 4, 0, 0, 0, 0, 0, 8, 0},
         {4, 0, 8, 0, 0, 0, 0, 11, 0},
         {0, 8, 0, 7, 0, 4, 0, 0, 2},
         {0, 0, 7, 0, 9, 14, 0, 0, 0},
         {0, 0, 0, 9, 0, 10, 0, 0, 0},
         {0, 0, 4, 0, 10, 0, 2, 0, 0},
         {0, 0, 0, 14, 0, 2, 0, 1, 6},
         {8, 11, 0, 0, 0, 0, 1, 0, 7},
         {0, 0, 2, 0, 0, 0, 6, 7, 0}
    };
    dijkstra(graph,4);

    printf("Hello World!\n");
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值