1
0

example.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /***********************************************************
  2. * You can use all the programs on www.c-program-example.com
  3. * for personal and learning purposes. For permissions to use the
  4. * programs for commercial purposes,
  5. * contact info@c-program-example.com
  6. * To find more C programs, do visit www.c-program-example.com
  7. * and browse!
  8. *
  9. * Happy Coding
  10. ***********************************************************/
  11. #include "stdio.h"
  12. #define infinity 999
  13. void dij(int n,int v,int cost[10][10],int dist[])
  14. {
  15. int i,u,count,w,flag[10],min;
  16. for(i=1;i<=n;i++)
  17. flag[i]=0,dist[i]=cost[v][i];
  18. count=2;
  19. while(count<=n)
  20. {
  21. min=99;
  22. for(w=1;w<=n;w++)
  23. if(dist[w]<min && !flag[w])
  24. min=dist[w],u=w;
  25. flag[u]=1;
  26. count++;
  27. for(w=1;w<=n;w++)
  28. if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
  29. dist[w]=dist[u]+cost[u][w];
  30. }
  31. }
  32. void main()
  33. {
  34. int n,v,i,j,cost[10][10],dist[10];
  35. clrscr();
  36. printf("\n Enter the number of nodes:");
  37. scanf("%d",&n);
  38. printf("\n Enter the cost matrix:\n");
  39. for(i=1;i<=n;i++)
  40. for(j=1;j<=n;j++)
  41. {
  42. scanf("%d",&cost[i][j]);
  43. if(cost[i][j]==0)
  44. cost[i][j]=infinity;
  45. }
  46. printf("\n Enter the source matrix:");
  47. scanf("%d",&v);
  48. dij(n,v,cost,dist);
  49. printf("\n Shortest path:\n");
  50. for(i=1;i<=n;i++)
  51. if(i!=v)
  52. printf("%d->%d,cost=%d\n",v,i,dist[i]);
  53. getch();
  54. }