我有一个搜索算法,应该解析整个树,找到所有可以匹配搜索查询的结果,并将它们全部作为列表返回。我意识到这并不是算法的重点,但我这样做是为了测试广度优先和深度优先搜索,以通过计时来了解最快的搜索结果。其他两个搜索按预期工作,但当我输入与 DFID 搜索目标相同的搜索信息时,我得到一个空列表。所以我知道我的数据是正确的,只是算法中的某些东西是错误的,我不知道是什么。我根据维基百科上的伪代码写了这个。这是我所拥有的:
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);
}
}
}
最佳答案
交换 zim-zam 建议的行并添加另一个 else(在 else if height > 0 之后)将 maxDepth 翻转为 false
关于java - 深度优先迭代加深算法不返回结果(java中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16018896/