Question: In Java implement the four missing methods from UndirectedGraph.java to perform a BFS import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; public class UndirectedGraph { // Class

In Java implement the four missing methods from UndirectedGraph.java to perform a BFS

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 adjVertices[];

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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!