Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
#include <stdio.h>
#include <malloc.h>
#define N 7
#define INFINITY 65000
int main()
/*---------------------main----------------------------*/
{
init();
minspanTree();
printRoad();
}
/*-----------------end-of-main---------------------------*/
/*------------------------------Prims MST
Algorithm------------------------------------------*/
void minspanTree()
{
V[0]->dist=0;
int temp;
while((temp=getMinIndex())!=-1)//for all element in the queue
{
int i=0;
for(i=0;i<N;i++)//find all adjoining house connected to this node.
{
if(Adj[temp][i]>0&&V[i]->queued==TRUE)
//if the neighboring house is not already connected with a road( that
is , has not been taken out of queue)
{
if(V[i]->dist>Adj[temp][i])
//check if the current road is the shortest road to that
house.
{
V[i]->pred=V[temp];// if yes, we add this shortest
path to our MST and set the predecessor
V[i]->dist=Adj[temp][i];
}
}
}
}
}
/*------------------------------Print all the road
-------------------------------------------*/
void printRoad()
{
int i=N-1;
int cost=0;
while(i>0){
printf("\n connect a road from %c to %c costing %d", V[i]->name,V[i]->pred-
>name,V[i]->dist);
cost =cost+V[i]->dist;
i--;
}
printf("\n total min cost = %d ", cost);
}