c·c++/c 프로그래밍

Dijkstra's algorithm

바로이순간 2013. 12. 16. 11:54

#include <stdio.h>

#define MAX 5

#define INFINITE 9999


int allselected(int selected[]) {

  int i;

  for(i=0;i<MAX;i+=1) {

    if(selected[i]==0) {

      return 0;

    }

  }

  return 1;

}


void shortpath(int cost[][MAX],int preced[],int distance[]) {

  int selected[MAX]={0};

  int current=0,i,k,dc,smalldist,newdist;

  for(i=0;i<MAX;i++)

    distance[i]=INFINITE;

  selected[current]=1;

  distance[0]=0;

  current=0;

  while(!allselected(selected)) {

    smalldist=INFINITE;

    dc=distance[current];

    for(i=0;i<MAX;i+=1) {

      if(selected[i]==0) {                                             

        newdist=dc+cost[current][i];

        if(newdist<distance[i]) {

          distance[i]=newdist;

          preced[i]=current;

        }

        if(distance[i]<smalldist) {

          smalldist=distance[i];

          k=i;

        }

      }

    }

    current=k;

    selected[current]=1;

  }

}

void showpath(int p[], int i) {

  if(i==0) {

    printf("A");

  } else  {

    showpath(p, p[i]);

    printf("->%c", 'A'+i);

  }

}     

int main() {

  int cost[MAX][MAX]= 

     {{INFINITE,400,60,20,INFINITE},

      {INFINITE,INFINITE,90,300,60},

      {200,80,INFINITE,10,INFINITE},

      {150,INFINITE,20,INFINITE,60},

      {INFINITE,INFINITE,INFINITE,40,INFINITE}};


  int i,preced[MAX]={0},distance[MAX];

  shortpath(cost,preced,distance);

  /*

  for(i=0;i<MAX;i+=1) {

    printf("%d\n",distance[i]);

  }

  printf("\n");

  */

  printf("A\n");

  for(i=1;i<MAX;i+=1) {

    showpath(preced, preced[i]);

    printf("->%c\n", 'A'+i);

  }


  return 0;

}

'c·c++ > c 프로그래밍' 카테고리의 다른 글

c언어란 무엇인가요? - c언어 독학 가능한가요?  (0) 2014.02.22
2차원 shuffle  (0) 2014.02.18
괴짜수(weird number) 출력하기  (0) 2013.12.02
유사완전수,괴짜수  (0) 2013.12.01
힙정렬  (0) 2013.11.11