关于Iterative Deepening Depth的问题首先在java中搜索

时间:2013-04-15 00:38:44

标签: java search tree iterative-deepening

我正在维基百科上查看伪代码并试图用它来编写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);
        }
    }

1 个答案:

答案 0 :(得分:2)

我认为您可以使用boolean maxDepth = false实例变量来实现此目的。在while循环的每次迭代中,如果maxDepth == true然后退出,则设置maxDepth = true。在dls到达depth == 0时,然后设置maxDepth = maxDepth && children.isEmpty(),即如果节点有子节点,则将maxDepth设置为false。

另外,将dls更改为void方法。将return node.data替换为results.add(node.data),其中resultsArrayListHashSet,具体取决于您是否要过滤掉重复项。

如果您总是想访问树中的每个节点,请按以下步骤修改dls

public void dls(ArrayList<String> results, Node node, String goal)
{
    if (node.data.contains(goal))
    {
        results.add(node.data);
    }
    for(Node child : node.children)
    {
        dls(child, goal, depth-1);
    }
}