-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimsDemo.java
More file actions
66 lines (61 loc) · 1.8 KB
/
PrimsDemo.java
File metadata and controls
66 lines (61 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAA;
/**
*
* @author dell
*/
import java.util.Scanner;
public class PrimsDemo {
public static void main(String[]args)
{
int i,j,k,n,source;
int w[][]=new int[20][20];
int visited[]=new int[20];
int minwt,totalcost=0,ev=0,sv=0;
Scanner in=new Scanner(System.in);
System.out.println("enter the no.of nodes");
n=in.nextInt();
System.out.println("enter the weight matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
w[i][j]=in.nextInt();
}
}
System.out.println("enter the source vertex to start");
source=in.nextInt();
for(i=1;i<=n;i++)
{
visited[i]=0;
}
visited[source]=1;
for(i=1;i<n;i++)
{
minwt=999;
for(j=1;j<=n;j++)
{
if(visited[j]==1)
{
for(k=1;k<=n;k++)
{
if(visited[k]!=1&&w[j][k]<minwt)
{
sv=j;
ev=k;
minwt=w[j][k];
}
}
}
}
totalcost+=minwt;
visited[ev]=1;
System.out.println(sv+" "+"-->"+" "+ev+" "+"cost"+" "+minwt);
}
System.out.println("the total cost of minimum spanning tree is:"+totalcost);
}
}