Create a class: AdjListGraph.java, and just submit AdjListGraph.java. where Plea
ID: 3817595 • Letter: C
Question
Create a class: AdjListGraph.java, and just submit AdjListGraph.java. where Please implement a graph by adjacency list Write a method: void dfs(){\TO-DO}; which can traverse a graph by DFS (stack based or recursive) The class adjListGraph.java will be test as public class Test {public static void main(String[] args) {AdjListGraph theGraph = new AdjListGraph (); theGraph.addVertex('A');//0 (start for dfs) theGraph.addVertex('B');//1 theGraph.addVertex('C');//2 theGraph.addVertex('D');//3 theGraph.addVertex('E');//4 theGraph.addVertex('F');//5 theGraph.addEdge(0, 1);//AB theGraph.addEdge(0, 2);//AC theGraph.addEdge(1, 3);//BD theGraph.addEdge(2, 4);//CE theGraph.addEdge(2, 3);//CD theGraph.addEdge(0, 3);//AD theGraph.addEdge(3, 4);//DE theGraph.addEdge(3, 5);//DE System.out.print ("dfs visits:----------------------- "); theGraph.dfs(); System.out.println();}//end main ()}Explanation / Answer
public void dfs()
{
vertexList[0].visited=true;//start with vertex 0 mark it as visited
display(0);//display the vertex
theStack.push(0);//push into stack
while(!isStack(isEmpty())
{
int v=getUnvisitedvertex(theStack.top());//get unvisited vertex from top of the stack
if(v==-1)//if no such vertex
theStack.pop();//pop the stack
else
vertexList[v].visited=true;
display(v);
theStack.push(v);
}
}
for(j=0;j<n;j++)//n is the number of vertices
vertexList[visited]=false;//reset the flags
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.