-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrims code
More file actions
104 lines (92 loc) · 2.51 KB
/
Prims code
File metadata and controls
104 lines (92 loc) · 2.51 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import java.util.*;
import java.lang.*;
import java.util.Scanner;
class excep extends Exception
{
public String toString()
{
return "Enter a valid number of vertices";
}
}
class solveprims
{
static void primsmeth(int num,int CM[][])
{
Scanner sc=new Scanner(System.in);
int sv;
System.out.println("enter the source vertex");
sv=sc.nextInt();
System.out.println("The spanning tree edges are");
int visited[]=new int[num];
int unvisited[]=new int[num];
for(int i=0;i<num;i++)
{
visited[i]=0;
unvisited[i]=1;
}
visited[sv-1]=1;
unvisited[sv-1]=0;
int ind=0,src=0;
int tc=0,count=1;
//*****************
for(int i=1;i<num;i++)
{
int min=99;
for(int j=0;j<num;j++)
{
if(visited[j]==1)
{
for(int k=0;k<num;k++)
{
if((unvisited[k]==1)&&(CM[j][k]!=999))
{
if(CM[j][k]<min)
{
min=CM[j][k];
src=j;
ind=k;
}
}
}
}
}
visited[ind]=1;
unvisited[ind]=0;
System.out.println((count++)+" edge is"+" "+(src+1)+"--->"+(ind+1));
tc=tc+min;
}
System.out.println("The total cost spent is "+tc);
}
}
public class Hehe {
public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter the number of vertices");
n=sc.nextInt();
if(n==0 || n<0)
{
throw new excep();
}
int j,i;
int CM[][]=new int[n][n];
System.out.println("Enter the adjacency matrix of size "+n+"x"+n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
CM[i][j]=sc.nextInt();
}
}
System.out.println("The entered adjacency matrix is");
for(int x[]:CM)
{
for(int y:x)
{
System.out.print(y+" ");
}
System.out.println();
}
solveprims.primsmeth(n,CM);
}// main
}