Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

task in the attached photos, The directed graph is: The undirected graph is: Hint:Inthe duver class duebare an antay hbels of Strings: Pass this arfay

task in the attached photos, The directed graph is:
The undirected graph is:
Hint:Inthe duver class duebare an antay hbels of Strings:
Pass this arfay to the Graph constructor:
Modify the instance variables and Constructor of Graph.java as follows:
int numVertices;
LinkedList[] adjacencyList;
String[] labels;
Graph(int numVertices, String[] labels){
this.labels = labels;
this.numVertices = numVertices;
adjacencyList = new LinkedList[numVertices];
for (int i =0; i adjacencyList.length; i++)
adjacencyList[i]= new LinkedList();
}
Then modify the following methods of Graph.java accordingly:
//To add a directed edge to graph
void addDirectedEdge(int v, int w){
// To be completed by students
}
//To add undirected edge to graph
void addUndirectedEdge(int v, int w){
// to be completed by students
}
void displayGraph(){
// to be completed by students
}
import java.util.*;
class Graph {
int numVertices;
LinkedList[] adjacencyList;
Graph(int numVertices){
this.numVertices = numVertices;
adjacencyList = new LinkedList[numVertices];
for (int i =0; i adjacencyList.length; i++)
adjacencyList[i]= new LinkedList();
}
//To add a directed edge to graph
void addDirectedEdge(int v, int w){
adjacencyList[v].add(w); // Add w to vs list.
}
//To add undirected edge to graph
void addUndirectedEdge(int v, int w){
adjacencyList[v].add(w);
adjacencyList[w].add(v);
}
void displayGraph(){
for (int i =0; i adjacencyList.length; i++){
System.out.println(i +"---->"+ adjacencyList[i]);
}
System.out.println();
}
}
public class GraphDriver {
// Driver program to test methods of graph class
public static void main(String[] args){
// Total 5 vertices in graph
Graph g = new Graph(5);
g.addDirectedEdge(1,0);
g.addDirectedEdge(0,2);
g.addDirectedEdge(2,1);
g.addDirectedEdge(0,3);
g.addDirectedEdge(1,4);
System.out.println("The directed graph is: ");
g.displayGraph();
Graph g2= new Graph(5);
g2.addUndirectedEdge(1,0);
g2.addUndirectedEdge(0,2);
g2.addUndirectedEdge(2,1);
g2.addUndirectedEdge(0,3);
g2.addUndirectedEdge(1,4);
System.out.println("The undirected graph is: ");
g2.displayGraph();
}
}
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored 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

Recommended Textbook for

Databases Illuminated

Authors: Catherine M. Ricardo, Susan D. Urban, Karen C. Davis

4th Edition

1284231585, 978-1284231588

Students also viewed these Databases questions