小编Thu*_*GMT的帖子

将广度优先搜索转换为深度优先搜索Java

自从我接触Java以来​​已经很长时间了,所以这看起来似乎是一个奇怪的问题.目前我在StackOverflow上找到了这个广度优先搜索代码,我在最后修改了它,但我会在这里发布原始代码.

public List<Node> getDirections(Node start, Node finish){
    List<Node> directions = new LinkedList<Node>();
    Queue<Node> q = new LinkedList<Node>();
    Node current = 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;
}
Run Code Online (Sandbox Code Playgroud)

我知道其他深度优先搜索算法,但我也被告知可以轻松地将广度优先搜索转换为深度优先搜索,如果对此代码执行而不是2个完全不同的代码,我会更好地理解它.

如何将其更改为深度优先搜索?

java algorithm search depth

0
推荐指数
1
解决办法
4168
查看次数

标签 统计

algorithm ×1

depth ×1

java ×1

search ×1