Advertisement
WarPro

jikstra

Nov 24th, 2014
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include<stdio.h>
  2. #define infinity 999
  3. void dij(int n,int v,int cost[10][10],int dist[])
  4. {
  5. int i,u,count,w,flag[10],min;
  6. for(i=1;i<=n;i++)
  7. flag[i]=0,dist[i]=cost[v][i];
  8. count=2;
  9. while(count<=n)
  10. {
  11. i=1;
  12. min=99;
  13. for(w=1;w<=n;w++)
  14. if(dist[w]<min && !flag[w])
  15. min=dist[w],u=w;
  16. flag[u]=1;
  17. count++;
  18. for(w=1;w<=n;w++)
  19. if((dist[u]+cost[u][w]<dist[w])&&!flag[w])
  20. dist[w]=dist[u]+cost[u][w];
  21. }
  22. }
  23. void main()
  24. {
  25. int n,v,i,j,cost[10][10],dist[10];
  26. printf("\n enter no. of nodes:");
  27. scanf("%d",&n);
  28. printf("\n enter cost matrix:");
  29. for(i=1;i<=n;i++)
  30. for(j=1;j<=n;j++)
  31. {
  32. scanf("%d",&cost[i][j]);
  33. if(cost[i][j]==0)
  34. cost[i][j]=infinity;
  35. }
  36. printf("\n enter source:");
  37. scanf("%d",&v);
  38. dij(n,v,cost,dist);
  39. printf("\n shortest path:");
  40. for(i=1;i<=n;i++)
  41. if(i!=v)
  42. printf("\n %d ->%d,cost=%d\n",v,i,dist[i]);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement