单源最短路径算法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;
}