add two depth first search methods, one recursive and non recursive in my graph.
ID: 3818134 • Letter: A
Question
add two depth first search methods, one recursive and non recursive in my graph.java class.
Eclipse File Edit Source Refactor Navigate Search Project Run Window Help D 100% Sat Apr 15 9:09:07 AM ROYAN HANSON a E workspace Java lab 13/src/dsf matrix forstudents/test,java Eclipse Quick Access Graph java Stack java D 'test java 23 3 class Test 4 csc 2720, Spring 2017 5 8 public class test 108 public static void main(String args) 11 Graph the Graph new Graph() the Graph addvertexC'A'); 0 (start for dfs) the Graph addvertexC'B') 1 14 the Graph 2 the Graph 3 the Graph addvertexC'E 4 the Graph addvertexC 4 the Graph. addEdge(0, 1); AB 20 the Graph add Edge(0, 2) AC the Graph add EdgeC 3) BD 22 the Graph add Edge(2, 4 CE 23 the Graph add Edge(2, 3) CD the Graph add Edge(0, 3) AD 25 the Graph add Edge(3, 4 DE 26 the Graph add (3, S) DE 27 28 System. out print("Stack based dfs visits 29 theGraph.dfsc); 30 System. out printinC) System. out print( recursive dfs visits 32 the Graph.recusive-dfsC0); 33 35 end main() 36 37 end class DFSApp 39 41 42 Writable Smart Insert 7:39 SONOSExplanation / Answer
//iterative program
public void dfs()
{
int source=start;
int number_of_nodes = MAX_VERTS-1;
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
System.out.print(element + " ");
visited[source] = 1;
theStack.push(source);
while (!theStack.isEmpty())
{
element = theStack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjMatrix[element][i] == 1 && visited[i] == 0)
{
theStack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + " ");
continue;
}
i++;
}
theStack.pop();
}
}
boolean [] visitMatrix = new boolean[MAX_VERTS];
//recursive method...
public void DftRecursive(int start)
{
int vertex=start;
visitMatrix[vertex] = true;
Console.Write(vertex + 1 + " ");
for (int neighbour = 0; neighbour < MAX_VERTS; neighbour++)
{
if (visitMatrix[neighbour] == false && adjMatrix[vertex][neighbour] == 1)
{
DftRecursive(neighbour);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.