skb461

prim’s algorithm

Jan 22nd, 2023
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | Source Code | 0 0
  1. #include<stdio.h>
  2.  
  3. int n, cost[10][10];
  4. void prim() {
  5. int i, j, startVertex, endVertex;
  6. int k, nr[10], temp, minimumCost = 0, tree[10][3];
  7.  
  8. temp = cost[0][0];
  9. for (i = 0; i < n; i++) {
  10. for (j = 0; j < n; j++) {
  11. if (temp > cost[i][j]) {
  12. temp = cost[i][j];
  13. startVertex = i;
  14. endVertex = j;
  15. }
  16. }
  17. }
  18. tree[0][0] = startVertex;
  19. tree[0][1] = endVertex;
  20. tree[0][2] = temp;
  21. minimumCost = temp;
  22.  
  23. for (i = 0; i < n; i++) {
  24. if (cost[i][startVertex] < cost[i][endVertex])
  25. nr[i] = startVertex;
  26. else
  27. nr[i] = endVertex;
  28. }
  29. nr[startVertex] = 100;
  30. nr[endVertex] = 100;
  31. temp = 99;
  32. for (i = 1; i < n - 1; i++) {
  33. for (j = 0; j < n; j++) {
  34. if (nr[j] != 100 && cost[j][nr[j]] < temp) {
  35. temp = cost[j][nr[j]];
  36. k = j;
  37. }
  38. }
  39. tree[i][0] = k;
  40. tree[i][1] = nr[k];
  41. tree[i][2] = cost[k][nr[k]];
  42. minimumCost = minimumCost + cost[k][nr[k]];
  43. nr[k] = 100;
  44.  
  45. for (j = 0; j < n; j++) {
  46. if (nr[j] != 100 && cost[j][nr[j]] > cost[j][k])
  47. nr[j] = k;
  48. }
  49. temp = 99;
  50. }
  51. printf("\nThe min spanning tree is:- ");
  52. for (i = 0; i < n - 1; i++) {
  53. for (j = 0; j < 3; j++)
  54. printf("%d", tree[i][j]);
  55. printf("\n");
  56. }
  57. printf("\nMin cost : %d", minimumCost);
  58. }
  59. void main() {
  60. int i, j;
  61. printf("\nEnter the no. of vertices :");
  62. scanf("%d", &n);
  63. printf("\nEnter the costs of edges in matrix form :");
  64. for (i = 0; i < n; i++)
  65. for (j = 0; j < n; j++) {
  66. scanf("%d", &cost[i][j]);
  67. }
  68. printf("\nThe matrix is : ");
  69. for (i = 0; i < n; i++) {
  70. for (j = 0; j < n; j++) {
  71. printf("%d\t", cost[i][j]);
  72. }
  73. printf("\n");
  74. }
  75. prim();}
  76.  
Advertisement
Add Comment
Please, Sign In to add comment