【发布时间】:2017-10-17 04:44:04
【问题描述】:
我正在尝试实现迭代深度搜索。我不知道我做错了什么,但我似乎没有做对。我总是以无限循环结束。 谁能指出我的错误? 我实现了深度有限搜索并在我的 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 类只有两个属性,Data 和 Children
【问题讨论】:
-
正如 Simone 所说,您使用错误的参数调用 DLS(使用 _depth 而不是 depth)。此外,您应该将深度上限限制为图形大小。您可以通过在预处理中计算图节点来做到这一点。
-
Int32.MaxValue;意味着它不会永远运行。等几年,它就会停止。
标签: c# algorithm search artificial-intelligence