Depth First Iterative deepening algorithm returning no results (in java)

非 Y 不嫁゛ 提交于 2019-12-11 18:18:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!