Advertisement
Guest User

diji

a guest
May 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<stdbool.h>
  4. #define inf 9999
  5. int n;
  6. void diji( int x[n][n] ,int s , int des )
  7. {
  8. int a[n][n] , d[n], p[n];
  9. bool visited [n];
  10. int mind=0 , next =0 , i,j;
  11. for (i=0;i<n;i++)
  12. { d[i]=0;
  13. for (j=0;j<n;j++)
  14. {
  15. if (x[i][j]==0)
  16. {
  17. a[i][j]=inf;
  18. }else{a[i][j]=x[i][j];}}}
  19.  
  20.  
  21. for (i=0;i<n;i++)
  22. {
  23. d[i] = a[s][i];
  24. p[i]=s;
  25. visited[i]=false;
  26.  
  27. }
  28.  
  29. d[s]=0;
  30. visited[s]=true;
  31. int ned = 1;
  32. while (ned < n-1 )
  33. {mind = inf;
  34. for(i=0;i<n;i++)
  35. {if (d[i]<mind&&visited[i]!=true){
  36. mind = d[i];
  37. next=i;
  38. }
  39.  
  40. }visited[next]=true;
  41. for(i=0;i<n;i++)
  42. {
  43. if (visited[i]==false)
  44. {
  45. if(mind+a[i][j]<d[i])
  46. {
  47. d[i]= mind +a[next][i];
  48. p[i]=next;
  49.  
  50. }
  51. }
  52. }
  53.  
  54. ned++;
  55.  
  56. }
  57.  
  58. for(i=0;i < n;i++){
  59. if(i== des)
  60. {
  61. printf("\n min distance from %d to %d = %d ",s, i, d[i]);
  62. printf("\nPath = %d", i);
  63. j=i;
  64. do
  65. {
  66. j=p[j];
  67. printf(" <- %d", j);
  68. }
  69. while(j!=s);
  70. }
  71. }
  72.  
  73.  
  74. }
  75.  
  76.  
  77. int main()
  78. {
  79. int i,j;
  80. printf("insert the number of ver :");
  81. scanf("%d",&n);
  82. int x[n][n];
  83. for (i=0;i<n;i++)
  84. {
  85. for (j=0;j<n;j++)
  86. {
  87. if(i==j)
  88. {
  89. x[i][j]=0;
  90. }else
  91. {
  92. printf("\n enter the weight of the edge from %d to %d \n ",i,j);
  93. scanf("%d",&x[i][j]);
  94. }
  95.  
  96. }
  97. }
  98. for (i=0;i<n;i++)
  99. {
  100.  
  101. for (j=0;j<n;j++)
  102. {
  103. printf("%d \t",x[i][j]);
  104. }
  105. printf("\n");
  106. }int s,des;
  107. printf("\n enter the starting node :\n");
  108. scanf("%d",&s);
  109. printf("\nenter the des node :\n");
  110. scanf("%d",&des);
  111. diji(x,s,des);
  112. return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement