dijkstra 알고리즘 C 언어 구현

2814 단어 데이터 구조
#include 
#include 
#include 
#define NUM 7

typedef struct MGraph		/*         */
{
     int edges[NUM][NUM];
     int n,e;
} MGraph;

MGraph *build_mgraph();
void Dijkstra(MGraph *mgraph, int v);
void Dispath(int dis[],int pre[],int visited[], int n, int v);
void Ppath(int path[], int i, int v);

int main(void)
{
     MGraph *mgraph;

     printf("
*************************************************************
"); printf(" :
"); mgraph=build_mgraph(); printf("
*************************************************************
"); printf("dijkstra :
"); Dijkstra(mgraph,0); printf("
*************************************************************
"); return 0; } MGraph *build_mgraph() { int i,j; int num_e=0; MGraph *mgraph=(MGraph *)malloc(sizeof(MGraph)); int matrix[NUM][NUM]={{0,4,6,6,INT_MAX,INT_MAX,INT_MAX}, {INT_MAX,0,1,INT_MAX,7,INT_MAX,INT_MAX}, {INT_MAX,INT_MAX,0,INT_MAX,6,4,INT_MAX}, {INT_MAX,INT_MAX,2,0,INT_MAX,5,INT_MAX}, {INT_MAX,INT_MAX,INT_MAX,INT_MAX,0,INT_MAX,6}, {INT_MAX,INT_MAX,INT_MAX,INT_MAX,1,0,8}, {INT_MAX,INT_MAX,INT_MAX,INT_MAX,INT_MAX,INT_MAX,0}}; for(i=0;iedges[i][j]=matrix[i][j]; if(matrix[i][j]!=0 && matrix[i][j]!=INT_MAX) num_e++; } } mgraph->n=NUM; mgraph->e=num_e; printf("node=%d;edges=%d
",mgraph->n,mgraph->e); for(i=0;iedges[i][j]!=INT_MAX) printf("%3d",mgraph->edges[i][j]); else printf("%3c",'&'); } printf("
"); } return mgraph; } void Dijkstra(MGraph *mgraph, int v) { int i,j; int no; int min_dis; int dis[NUM]; int visited[NUM]={0}; int pre[NUM]; visited[v]=1; for(i=0;in;i++) { dis[i]=mgraph->edges[v][i]; pre[i]=v; } for(i=0;in;i++) { min_dis=INT_MAX; for(j=0;jn;j++) { if(!visited[j] && dis[j]n;j++) { if(!visited[j] && mgraph->edges[no][j]!=INT_MAX && dis[no]+mgraph->edges[no][j] < dis[j]) { dis[j]=dis[no]+mgraph->edges[no][j]; pre[j]=no; } } } Dispath(dis,pre,visited,mgraph->n,v); } void Dispath(int dis[],int pre[],int visited[], int n, int v) { int i; for(i=0;i

좋은 웹페이지 즐겨찾기