Converting a Breadth First Search to Depth first Search in Java
its been a long time since I touched Java so this may seem like an odd question. Currently have this Breadth First Search code I found here on StackOverflow, I have it modified on my end but I'll post the original code here.
public List<Node> getDirections(Node start, Node finish){
List<Node> directions = new LinkedList<Node>();
Queue<Node> q = new LinkedList<Node>();
Node cu开发者_C百科rrent = start;
q.add(current);
while(!q.isEmpty()){
current = q.remove();
directions.add(current);
if (current.equals(finish)){
break;
}else{
for(Node node : current.getOutNodes()){
if(!q.contains(node)){
q.add(node);
}
}
}
}
if (!current.equals(finish)){
System.out.println("can't reach destination");
}
return directions;
}
I'm aware of other depth first search algorithms out there, but I was also told its possible to convert breadth first search to depth first search easily, and I would understand it better if it was done to this code instead of 2 totally different codes.
How can I change this to be a Depth First Search?
The main difference between Depth first and Breadth fist is the order in which you explore the nodes in your "frontier" (the list of nodes you're yet to explore).
If you add the outgoing nodes from your current node to the end of that list, you'll be testing every possibility in a "level" (for simplification purposes, imagine this as a tree), before going to the next level, so you have a Breadth first search.
If, on the other hand, you explore the newly added nodes (the outgoing nodes from your current position), before the nodes you've added earlier (that belong in the "upper" levels of the tree), then you'll be exploring the depth of the tree first.
In terms of data structures, you want a Stack instead of a Queue, but I think the explanation may come in handy.
You'd have to replace q.add(node)
(which adds at the end of a list) with q.add(0, node)
(to add at the beginning). Basically, use a stack
instead of a queue
.
Obviously you'd have to use the List
interface instead of the Queue
one to access the LinkedList
.
Deque<Node> q = new LinkedList<Node>();
and use pop
and push
instead of remove
and add
basically remove from the same side you added (normal remove
and add
are LIFO queue base ops) depth first uses a FIFO stack
and the other search algorithms are essentially the same but use different types of queues (eager search uses a easiest next step for example)
Replace Queue
and LinkedList
with Stack
, add
with push
, and remove
with pop
精彩评论