Question: I ' m learning depth - first search, and for some reason, my output is different from the correct output. The correct output should be
Im learning depthfirst search, and for some reason, my output is different from the correct output. The correct output should be DFS: A E F G B C D However, my code switches the last two nodes, giving the result of DFS: A E F G B D C The only part of the program that can be modified is the depthFirstSearch method.
I would love to know what Im doing wrong.
GraphInfo.txt NOT MODIFIABLE
ACDE
BE
CAEFG
DAE
EABCDF
FCEG
GCF
Node.javaNOT MODIFIABLE
import java.util.ArrayList;
public class Node
private String name;
private ArrayList adjancencyList;
public NodeString name
this.name name;
adjancencyList new ArrayList;
public String getName
return name;
public ArrayList getAdjacencyList
return adjancencyList;
public void addAdjacentNodeNode n
adjancencyList.addn;
@Override
public boolean equalsObject o
ifo instanceof Node
return false;
Node n Node o;
return this.name.equalsIgnoreCasenname;
public String toString
String str "Node: name Adjacency List:";
forNode a : adjancencyList
str agetName;
return str;
Graph.java ONLY the depthFirstSearch method is modifiable
import java.util.ArrayList;
import java.util.Scanner;
import java.ioFile;
import java.ioIOException;
import java.util.Stack;
public class Graph
public static void mainString args throws IOException
ArrayList graph createGraph;
displayGraphgraph;
depthFirstSearchgraph;
public static ArrayList createGraph throws IOException
ArrayList graph new ArrayList;
File file new FileGraphInfotxt;
Scanner inputFile new Scannerfile;
whileinputFilehasNext
String line inputFile.nextLine;
String tokens line.split;
iftokenslength
Node n new Nodetokens;
int nodeIndex graph.indexOfn;
ifnodeIndex
n graph.getnodeIndex;
else
graph.addn;
forint i ; i tokens.length; i
Node adj new Nodetokensi;
int adjNodeIndex graph.indexOfadj;
ifadjNodeIndex
adj graph.getadjNodeIndex;
else
graph.addadj;
naddAdjacentNodeadj;
return graph;
public static void displayGraphArrayList graph
forNode n : graph
System.out.printlnn;
public static void depthFirstSearchArrayList graph
System.out.printlnDFS:;
Node startNode graph.get;
Stack stack new Stack;
ArrayList visitedSet new ArrayList;
visitedSet.addstartNode;
stack.pushstartNode;
while stack.isEmpty
Node currentNodestack.pop;
visitedSet.addcurrentNode;
System.out.printcurrentNodegetName;
ArrayList adjacentNodes currentNode.getAdjacencyList;
for Node adjNode : adjacentNodes
if visitedSet.containsadjNode
visitedSet.addadjNode;
stack.pushadjNode;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
