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

Need a simple exercise with a graph based on an adjacency list. provide two meth

ID: 3710312 • Letter: N

Question

Need a simple exercise with a graph based on an adjacency list. provide two method implementations for the following class:

import java . util . Map ;
import java . util . Set ;
import java . util . List ;

public class Graph <T > {
public Graph () {
adjacency = new java . util . HashMap < >();
}
public void addEdge (T start , T end )
{
}
public boolean testPath ( List <T > vertexList )
{
}
private Map <T , Set <T >> adjacency ;
}

the following methods are needed:
1. void addEdge(T start, T end) This code adds the directed edge (start, end) to the graph. In the map adjacency, get or create the Set associated with start, and add end to this Set.
2. boolean testPath(List vertexList) This method should return true if each consecutive pair of vertices in the list exists in the graph, false otherwise. Throw an exception if vertexList doesn’t have at least one edge’s worth of vertices in it!

Explanation / Answer

package chegg;

import java . util . Map ;

import java . util . Set ;

import java.util.HashSet;

import java . util . List ;

public class Graph <T > {

public Graph () {

adjacency = new java.util.HashMap< >();

}

public void addEdge (T start , T end )

{

//creating a set for the end object

Set<T> set = new HashSet<>();

set.add(end);

//adding both start and set of end as an edge to the adjacency Map

adjacency.put(start,set);

}

public boolean testPath( List <T > vertexList ){

//throwing exception if vertex list has no elements

if (vertexList == null || vertexList.size() == 0)

try {

throw new Exception();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// iterating through each element and checking the adjacency map if the adjacent element is present in the set

for(int i=0;i<vertexList.size()-1;i++){

//if adjacent element is not present then returning false

if(!adjacency.get(vertexList.get(i)).contains(vertexList.get(i+1))) return false;

}

//if the whole path is present in the map, returning true

return true;

}

private Map <T , Set <T >> adjacency ;

}

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