Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use Java to implement Prim\'s Algorithm. The program should prompt the user to e

ID: 3734221 • Letter: U

Question

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: <to> <from>");
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();
}
}

Explanation / Answer

Following is the Java Program:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote