So I wrote a Graph class and I can’t seem to do a depth first search on it properly depending on the sequencing of nodes. Here’s what I mean:
If my graph looks like this:
A-B-D
|/
C
The DFS returns: “ABC”
But when it looks like this:
A-B
| |
D C
|
E
It will print ABCDE correctly.
The problem I’ve found lies in my getUnvisitedAdjacentNode() function. Here is the function:
public int getUnvisitedAdjacentNode(int n) {
for (int i = 0; i < this.nodeList.size(); i++) {
if (this.edges[n][i] == 1 && this.nodeList.get(i).wasVisited == false) {
return i;
}
}
return -1;
}
The problem, I’ve found is because it goes in “order” (just a for loop) , it will never get traverse D in the first situation because B gets visited and after C gets visited, B simply get’s popped off of the stack. Maybe this isn’t the problem.
Here’s the code for my actual DFS traversal.
public void depthFirstTraverse() {
Stack<Node> stack = new Stack<Node>();
nodeList.get(0).wasVisited = true;
System.out.println(nodeList.get(0).item);
stack.push(nodeList.get(0));
while (!stack.isEmpty()) {
int nextNode = this.getUnvisitedAdjacentNode(stack.peek().index);
if (nextNode == -1) {
stack.pop();
} else {
nodeList.get(nextNode).wasVisited = true;
System.out.println(nodeList.get(nextNode).item);
stack.push(nodeList.get(nextNode));
}
}
for (int i = 0; i < nodeList.size(); i++) {
nodeList.get(i).wasVisited = false;
}
}
Fortunately I found my own mistake, the code above is all correct, except it was in the code that I hadn’t pasted.
In case anybody cares, the problem lied in the fact that I completely disregarded the fact that ArrayLists have an “IndexOf()” method (stupid, I know) and decided to hack my own “index” field into my Node class. When dealing with my own indices, I had a minor bug which screwed up the traversal.
So the old line in my DFS algorithm looks like this:
But it should be: