【发布时间】: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