Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<conio.h>
  3.  
  4. int n, cost[10][10];
  5.  
  6. void prim() {
  7. int i, j, startVertex, endVertex;
  8. int k, nr[10], temp, minimumCost = 0, tree[10][3];
  9.  
  10. /* For first smallest edge */
  11. temp = cost[0][0];
  12. for (i = 0; i < n; i++) {
  13. for (j = 0; j < n; j++) {
  14. if (temp > cost[i][j]) {
  15. temp = cost[i][j];
  16. startVertex = i;
  17. endVertex = j;
  18. }
  19. }
  20. }
  21. /* Now we have fist smallest edge in graph */
  22. tree[0][0] = startVertex;
  23. tree[0][1] = endVertex;
  24. tree[0][2] = temp;
  25. minimumCost = temp;
  26.  
  27. /* Now we have to find min dis of each vertex from either
  28. startVertex or endVertex by initialising nr[] array
  29. */
  30.  
  31. for (i = 0; i < n; i++) {
  32. if (cost[i][startVertex] < cost[i][endVertex])
  33. nr[i] = startVertex;
  34. else
  35. nr[i] = endVertex;
  36. }
  37.  
  38. /* To indicate visited vertex initialise nr[] for them to 100 */
  39. nr[startVertex] = 100;
  40. nr[endVertex] = 100;
  41.  
  42. /* Now find out remaining n-2 edges */
  43. temp = 99;
  44. for (i = 1; i < n - 1; i++) {
  45. for (j = 0; j < n; j++) {
  46. if (nr[j] != 100 && cost[j][nr[j]] < temp) {
  47. temp = cost[j][nr[j]];
  48. k = j;
  49. }
  50. }
  51. /* Now i have got next vertex */
  52. tree[i][0] = k;
  53. tree[i][1] = nr[k];
  54. tree[i][2] = cost[k][nr[k]];
  55. minimumCost = minimumCost + cost[k][nr[k]];
  56. nr[k] = 100;
  57.  
  58. /* Now find if k is nearest to any vertex
  59. than its previous near value */
  60.  
  61. for (j = 0; j < n; j++) {
  62. if (nr[j] != 100 && cost[j][nr[j]] > cost[j][k])
  63. nr[j] = k;
  64. }
  65. temp = 99;
  66. }
  67. /* Now i have the answer, just going to print it */
  68. printf("\nThe min spanning tree is:- ");
  69. for (i = 0; i < n - 1; i++) {
  70. for (j = 0; j < 3; j++)
  71. printf("%d", tree[i][j]);
  72. printf("\n");
  73. }
  74.  
  75. printf("\nMin cost : %d", minimumCost);
  76. }
  77.  
  78. void main() {
  79. int i, j;
  80. clrscr();
  81.  
  82. printf("\nEnter the no. of vertices :");
  83. scanf("%d", &n);
  84.  
  85. printf("\nEnter the costs of edges in matrix form :");
  86. for (i = 0; i < n; i++)
  87. for (j = 0; j < n; j++) {
  88. scanf("%d", &cost[i][j]);
  89. }
  90.  
  91. printf("\nThe matrix is : ");
  92. for (i = 0; i < n; i++) {
  93. for (j = 0; j < n; j++) {
  94. printf("%d\t", cost[i][j]);
  95. }
  96. printf("\n");
  97. }
  98. prim();
  99. getch();
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement