Facebook
From shashank, 4 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 138
  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<stdlib.h>
  4. int a,b,u,v,n,i,j,ne=1;
  5. int visited[10]= {
  6.         0
  7. }
  8. ,min,mincost=0,cost[10][10];
  9. void main() {
  10.         system("cls");
  11.         printf("\n Enter the number of nodes:");
  12.         scanf("%d",&n);
  13.         printf("\n Enter the adjacency matrix:\n");
  14.         for (i=1;i<=n;i++)
  15.           for (j=1;j<=n;j++) {
  16.                 scanf("%d",&cost[i][j]);
  17.                 if(cost[i][j]==0)
  18.                     cost[i][j]=999;
  19.         }
  20.         visited[1]=1;
  21.         printf("\n");
  22.         while(ne<n) {
  23.                 for (i=1,min=999;i<=n;i++)
  24.                    for (j=1;j<=n;j++)
  25.                     if(cost[i][j]<min)
  26.                      if(visited[i]!=0) {
  27.                         min=cost[i][j];
  28.                         a=u=i;
  29.                         b=v=j;
  30.                 }
  31.                 if(visited[u]==0 || visited[v]==0) {
  32.                         printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
  33.                         mincost+=min;
  34.                         visited[b]=1;
  35.                 }
  36.                 cost[a][b]=cost[b][a]=999;
  37.         }
  38.         printf("\n Minimun cost=%d",mincost);
  39.         getch();
  40. }
  41.