问题
I have a search algorithm that is supposed to parse the entire tree, find all results that could match a search query, and return them all as a list. I realize this isn't quite the point of the algorithm, but I'm doing this as a test with breadth first and depth first searches to see what is fastest by timing them. The other two searches work as intended, but when I enter the same search information as my goal for the DFID search i get an empty list. So I know my data is right, just something in the algorithm is wrong and I can't figure out what. I wrote this based off the pseudocode on Wikipedia. Here's what I have:
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);
}
}
}
回答1:
swap the lines zim-zam suggested and add another else (after the else if depth > 0 ) to flip maxDepth to false
来源:https://stackoverflow.com/questions/16018896/depth-first-iterative-deepening-algorithm-returning-no-results-in-java