×
NOTE!
Click on MENU to Browse between Subjects...
Advertisement
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY
(Effective from the academic year 2018 -2019)
SEMESTER - IV
Course Code 18CSL47
CIE Marks 40
Number of Contact Hours/Week 0:2:2
SEE Marks 60
Total Number of Lab Contact Hours 36
Exam Hours 03
Advertisement
Experiments 9
Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's algorithm
Advertisement
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 | import java.util.Scanner; class Prim { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter Number of Vertices"); int n = scan.nextInt(); int[][] costMatrix = new int[n][n]; boolean[] visited = new boolean[n]; System.out.println("Enter Cost Adjacency Matrix"); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) costMatrix[i][j] = scan.nextInt(); for (int i = 0; i < n; i++) visited[i] = false; System.out.println("Enter Source Vertex"); int srcVertex = scan.nextInt(); scan.close(); visited[srcVertex - 1] = true; int source = 0, cost = 0, target = 0; System.out.print("Edges: "); for (int i = 1; i < n; i++) { int min = Integer.MAX_VALUE; for (int j = 0; j < n; j++) { if (visited[j]) { for (int k = 0; k < n; k++) { if (!visited[k] && min > costMatrix[j][k]) { min = costMatrix[j][k]; source = j; target = k; } } } } visited[target] = true; System.out.print("(" + (source + 1) + "," + (target + 1) + ")"); cost += min; } System.out.println("\nMinimum cost of Spanning Tree: " + cost); } } |
Advertisement
Fig 9: Output .
Advertisement
×
Note
Please Share the website link with Your Friends and known Students...
-ADMIN
-ADMIN
×
Note
Page Number is specified to navigate between Pages...
T = Text book
QB = Question Bank
AS = Amswer Script
-ADMIN
T = Text book
QB = Question Bank
AS = Amswer Script
-ADMIN
Advertisement