迭代深化C#中的搜索

时间:2017-05-17 15:53:06

标签: c# algorithm search artificial-intelligence

我正在尝试实施Iterative Deeping Search。我不知道我做错了什么,但我似乎没有做对。我总是以无限循环结束。 谁能指出我的错误? 我实施了深度限制搜索并在我的IDS代码中使用它。 DLS本身似乎运行良好,但我不了解IDS以及为什么我最终会陷入无限循环。

public class IterativeDeepeningSearch<T>  where T : IComparable
{
    string closed;

    public int maximumDepth;
    public int depth = 0;
    bool Found = false;
    Stack<Vertex<T>> open;

    public IterativeDeepeningSearch()
    {
        open = new Stack<Vertex<T>>();
    }

    public bool IDS(Vertex<T> startNode, Vertex<T> goalNode)
    {
        // loops through until a goal node is found
        for (int _depth = 0; _depth < Int32.MaxValue; _depth++)
        {
            bool found = DLS(startNode, goalNode, _depth);
            if (found)
            {
                return true;
            }
        }
        // this will never be reached as it 
        // loops forever until goal is found
        return false;
    }

    public bool DLS(Vertex<T> startNode, Vertex<T> goalNode, int _maximumDepth)
    {
        maximumDepth = _maximumDepth;

        open.Push(startNode);  

        while (open.Count > 0 && depth < maximumDepth)    
        {
            Vertex<T> node = open.Pop();    

            closed = closed + " " + node.Data.ToString();
            if (node.Data.ToString() == goalNode.Data.ToString())
            {
                Debug.Write("Success");
                Found = true;
                break;

            }

            List<Vertex<T>> neighbours = node.Neighbors;   

            depth++;    

            if (neighbours != null)
            {
                foreach (Vertex<T> neighbour in neighbours)
                {
                    if (!closed.Contains(neighbour.ToString()))
                        open.Push(neighbour);   
                }
                Debug.Write("Failure");
            }


        }
        Console.WriteLine(closed);
        return Found;
    }

}
}

PS:我的Vertex Class只有两个属性,Data和Children

1 个答案:

答案 0 :(得分:1)

for循环在_depth上迭代,但在DLS函数中,你传递的是深度,总是为0

    for (int _depth = 0; _depth < Int32.MaxValue; _depth++)
    {
        bool found = DLS(startNode, goalNode, depth);
        if (found)
        {
            return true;
        }
    }