【问题标题】:Depth First Iterative deepening algorithm returning no results (in java)深度优先迭代深化算法不返回结果(在java中)
【发布时间】:2013-04-15 15:20:36
【问题描述】:

我有一个搜索算法,它应该解析整个树,找到所有可以匹配搜索查询的结果,并将它们全部作为列表返回。我意识到这并不是算法的重点,但我这样做是为了进行广度优先和深度优先搜索的测试,以通过计时来查看最快的搜索结果。其他两个搜索按预期工作,但是当我输入与 DFID 搜索目标相同的搜索信息时,我得到一个空列表。所以我知道我的数据是正确的,只是算法中有问题,我不知道是什么。我是根据 Wikipedia 上的伪代码编写的。这是我所拥有的:

boolean maxDepth = false;
List<String> results = new ArrayList<String>();

public List<String> dfid(Tree t, String goal)
{
    int depth = 0;

    while (!maxDepth)
    {
        System.out.println(results);
        maxDepth = true;
        depth += 1;
        dls(t.root, goal, depth);
    }
    return results;
}

public void dls(Node node, String goal, int depth)
{
    System.out.println(depth);
    if (depth == 0 && node.data.contains(goal))
    {
        //set maxDepth to false if the node has children
        if (!node.children.isEmpty())
        {
            maxDepth = false;
        }
        results.add(node.data);
    }
    else if (depth > 0)
    {
        for(Node child : node.children)
        {
            dls(child, goal, depth-1);
        }
    }
}

【问题讨论】:

  • 目标是你想要找到的某个东西吗?
  • node.data 是什么类类型?如果 node.data.contains(goal) 返回 false,则您的 dls() 方法将在给定深度停止:因此,永远不会检查 node.data.contains(goal) 返回 true 的任何子级。
  • @torquestomp 几乎是正确的,但是检查孩子是否为空可以确保您仍然继续在 dfid 中的 while 循环
  • @torquestomp node.data 是一个字符串。
  • 再想一想,node.data.contains(goal) 是有问题的并且非常不稳定。改变检查树尾的方式。另一件事:for(Node child : node.children) 会在树的每个节点上冒险吗?

标签: java search depth-first-search iterative-deepening


【解决方案1】:

交换 zim-zam 建议的行并添加另一个 else(在 else if depth > 0 之后)以将 maxDepth 翻转为 false

【讨论】:

  • @torquestomp 很好地注意到了你没有确保在所有树上移动的问题;您有时会到达将 maxDepth 翻转为 true 的地块,但您应该在树的另一边冒险,但由于它被翻转为 true,退出 dls 并返回 dfid,您应该在应该退出之前退出。 换句话说:给它的是你说你把它当作二叉树,你只会走它的一侧并过早退出。
猜你喜欢
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 2013-04-07
  • 2019-09-16
  • 1970-01-01
相关资源
最近更新 更多