我正在查看 Wikipedia 上的伪代码,并尝试使用它在 java 中编写算法。我的问题在于返回结果的方式有所不同。在维基百科上,返回一个结果,这超出了搜索范围。在我的情况下,每次找到相关节点时,都会将其添加到列表中,并且在处理完树后返回该列表。我将如何检测树的末端以打破并返回列表?
维基百科:
IDDFS(root, goal)
{
depth = 0
repeat
{
result = DLS(root, goal, depth)
if (result is a solution)
return result
depth = depth + 1
}
}
DLS(node, goal, depth)
{
if (depth == 0 and node == goal)
return node
else if (depth > 0)
for each child in expand(node)
DLS(child, goal, depth-1)
else
return null
}
矿:
public List<String> dfid(Tree t, String goal)
{
List<String> results = new ArrayList<String>();
String result;
int depth = 0;
while (true) //obviously not the way to go here
{
result = dls(t.root, goal, depth);
if (result.contains(goal))
results.add(result);
depth += 1;
}
return results; //unreachable return
}
public String dls(Node node, String goal, int depth)
{
if (depth == 0 && node.data.contains(goal))
{
return node.data;
}
else if (depth > 0)
{
for(Node child : node.children)
{
dls(child, goal, depth-1);
}
}
return null;
}
编辑:更改后:
//depth first iterative deepening
//control variables for these methods
boolean maxDepth = false;
List<String> results = new ArrayList<String>();
public List<String> dfid(Tree t, String goal)
{
int depth = 0;
while (!maxDepth)
{
maxDepth = true;
dls(t.root, goal, depth);
depth += 1;
}
return results;
}
public void dls(Node node, String goal, int depth)
{
if (depth == 0 && node.data.contains(goal))
{
//set maxDepth to false if the node has children
maxDepth = maxDepth && children.isEmpty();
results.add(node.data);
}
for(Node child : node.children)
{
dls(child, goal, depth-1);
}
}