Question
In Java complete the methods as indicated in the code import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; public class UndirectedGraph { // Class to represent a
In Java complete the methods as indicated in the code
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class UndirectedGraph {
// Class to represent a graph using adjacency list
// and the number of nodes
static class Graph{
int Nodes;
LinkedList
int[][] adjMatrix;
public Graph(int n){
this.Nodes = n;
adjVertices = new LinkedList[Nodes];
adjMatrix = new int[Nodes][Nodes];
for(int i = 0; i < Nodes; i++){
adjVertices[i] = new LinkedList
}
}
}
// Add an edge between two given vertices
static void addEdge(Graph graph, int src, int dst){
graph.adjVertices[src].addFirst(dst);
graph.adjVertices[dst].addFirst(src);
}
// Create the adjacency matrix representation
static void generateMatrix(Graph graph){
// Implement this method
}
// print the adjacency matrix
static void printMatrix(Graph graph){
// Implement this method
}
// Print the graph as adjacency list
static void printGraph(Graph graph){
// Implement this method
}
static void BFS(Graph graph, int s){
// Implement breadth first search
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("How many vertices?: ");
int nodeCount = input.nextInt();
Graph graph = null;
if(nodeCount > 0){
graph = new Graph(nodeCount);
}
System.out.println("Enter the edges between two nodes(counting from 0), -1 to stop");
while(true){
int src = input.nextInt();
if(src == -1) break;
int dest = input.nextInt();
if((src > nodeCount - 1) || (dest > nodeCount - 1)){
System.out.println("Invalid vertex.");
} else{
addEdge(graph, src, dest);
}
}
System.out.println("Enter your choices: "
+ "1 print adjacency list "
+ "2 print adjacency matrix "
+ "3 print breadth first search ");
int choice = input.nextInt();
switch(choice){
case 1:
printGraph(graph);
break;
case 2:
generateMatrix(graph);
printMatrix(graph);
break;
case 3:
System.out.println("Enter the beginning vertex:");
int source = input.nextInt();
System.out.println("BFS traversal of the graph starting at " + source);
BFS(graph, source);
}
input.close();
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started