Skip to content

Commit ace56c5

Browse files
The implementation of Prim's Algorithm is shown.
Prim's Algorithm is used to find the shortest path between any two points. Here the code uses Adjacency matrix as input and calculate the shortest past with minimum cost
1 parent 7f35408 commit ace56c5

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

prims.c

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
=======================================================================================================
2+
/*TIME COMPLEXITY
3+
PRIM'S ALGORITHM*/
4+
5+
#include<stdio.h>
6+
#include<time.h>
7+
8+
int a,b,u,v,n,i,j,ne=1; //global variables defined
9+
int visited[10]={0},min,mincost=0,cost[10][10]; //global array defined
10+
int main()
11+
{
12+
clock_t s,end;
13+
float t;
14+
printf(" Enter the number of nodes:"); //nodes for the graph
15+
scanf("%d",&n);
16+
printf(" Enter the adjacency matrix:\n"); //for connection between nodes
17+
for(i=1;i<=n;i++)
18+
for(j=1;j<=n;j++) //taking cost between nodes
19+
{
20+
scanf("%d",&cost[i][j]);
21+
if(cost[i][j]==0)
22+
cost[i][j]=999; //initialising all nodes to infinity
23+
}
24+
visited[1]=1; //selecting base node
25+
printf("\n");
26+
s=clock(); //starting the clock time
27+
while(ne<n)
28+
{
29+
for(i=1,min=999;i<=n;i++)
30+
for(j=1;j<=n;j++)
31+
if(cost[i][j]<min)
32+
if(visited[i]!=0) //if node is not visited
33+
{
34+
min=cost[i][j]; //select minimum cost between i and j
35+
a=u=i; //store it
36+
b=v=j;
37+
}
38+
if(visited[u]==0 || visited[v]==0) //if any one is visited
39+
{
40+
printf("n Edge %d:(%d %d) cost:%d",ne++,a,b,min); //print
41+
mincost+=min;
42+
visited[b]=1;
43+
}
44+
cost[a][b]=cost[b][a]=999;
45+
}
46+
end=clock(); //end clock time
47+
t=(double)((s-end)/CLOCKS_PER_SEC); //total time elapsed to perform
48+
printf("Time taken to perform Prim's alogrithm is : %f",t);
49+
printf("\n Minimun cost=%d",mincost);
50+
return 0;
51+
}
52+
53+
========================================================================================================================

0 commit comments

Comments
 (0)