Answered step by step
Verified Expert Solution
Link Copied!

Question

00
1 Approved Answer

Use Java to implement Prim's Algorithm. The program should prompt the user to enter the number of vertices and edges. Then, display the adjacency matrix

Use Java to implement Prim's Algorithm. The program should prompt the user to enter the number of vertices and edges. Then, display the adjacency matrix of the graph before Prim's algorithm is used, and after Prim's algorithm is used. The graph to use: https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Minimum_spanning_tree.svg/300px-Minimum_spanning_tree.svg.png Code: import java.util.Scanner; public class PrimsAlgo { private final int vert;//vertices for the graph private int[][] adjmat;//adjacency matrix for the graph public PrimsAlgo(int v) { vert = v; adjmat = new int[vert + 1][vert + 1]; } //t = to, f = from, e = edge of the graph public void makeEdge(int t, int f, int e) { try { adjmat[t][f] = e; } catch (ArrayIndexOutOfBoundsException index) { System.out.println("The vertices does not exists"); } } //method for getting the edge of the graph public int getEdge(int t, int f) { try { return adjmat[t][f]; } catch (ArrayIndexOutOfBoundsException index) { System.out.println("The vertices does not exists"); } return -1; } public static void main(String args[]) { int v, e, c = 1, t = 0, f = 0; Scanner sc = new Scanner(System.in); PrimsAlgo graph; try { System.out.println("Enter the number of vertices: "); v = sc.nextInt(); System.out.println("Enter the number of edges: "); e = sc.nextInt(); graph = new PrimsAlgo(v); System.out.println("Enter the edges: "); while (c <= e) { t = sc.nextInt(); f = sc.nextInt(); graph.makeEdge(t, f, 1); c++; } System.out.println("The adjacency matrix for the original graph you entered is: "); System.out.print(" "); for (int i = 1; i <= v; i++) System.out.print(i + " "); System.out.println(); for (int i = 1; i <= v; i++) { System.out.print(i + " "); for (int j = 1; j <= v; j++) System.out.print(graph.getEdge(i, j) + " "); System.out.println(); } } catch (Exception E) { System.out.println("Whoops..something's not right here..."); } sc.close(); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions