我试图在2d数组(迷宫)中实现迭代加深搜索 .
static void Run_Ids(int x, int y)
{
int depth_limit = 0;
while(!cutoff)
{
out.println("Doing search at depth: " + depth_limit);
depthLimitedSearch(x, y, depth_limit);
depth_limit++;
}
}
这是我使用堆栈的有限深度优先搜索 . 出于某种原因,它在两个单元之间来回传递 . 它不会像它应该扩展 . 我认为我的DFS算法有问题 .
static void depthLimitedSearch(int x, int y, int depth){
Pair successor; //pair is the x, y co-ordinate
successor = starting(); //set the successor to starting cell
stack = new Stack<>();
int i = 0;
stack.push(successor);
while (!stack.isEmpty())
{
out.println("i level: " + i);
Pair parent = stack.peek(); //pop it here?
if (parent.x == Environment.goal[0] && parent.y == Environment.goal[1]){ //check to see if it is the goal
cutoff = true;
out.println("goal found ");
break;
}
if (i == depth){
//stack.pop(); //pop here?
break;
}
else{
Pair leftPos,rightPos,upPos,downPos;
leftPos = leftPosition(parent.x, parent.y);
rightPos = rightPosition(parent.x, parent.y);
upPos = upPosition(parent.x, parent.y);
downPos = downPosition(parent.x, parent.y);
if(Environment.isMovePossible(rightPos.x, rightPos.y))
//if it can go right
stack.push(rightPos);
if(Environment.isMovePossible(leftPos.x, leftPos.y))
// if it can go left
stack.push(leftPos);
if(Environment.isMovePossible(downPos.x, downPos.y))
//if it can go down
stack.push(downPos);
if(Environment.isMovePossible(upPos.x, upPos.y))
//if it can go up
stack.push(upPos);
stack.pop(); //pop here?
} //else
i++;
}//while
}
我没有那么多堆栈的经验,我很困惑在哪里推它和在哪里弹出 . 如果这里有人能指出我正确的方向,那就太好了!
1 回答
我认为你必须标记你已经访问过的数组的位置,以避免重新访问它们 . 不要将已经访问过的任何位置推到堆栈 .
如果不这样做,你很可能会陷入无限循环:
例如,假设从您的初始位置开始,您可以向所有方向前进 - 左,右,上和下 . 所以你推动这4个位置,然后弹出你推下的最后一个位置 .
现在,只要向下是一个有效的方向,你就会继续下去 . 当你到达一个你无法下降的位置时,你将推动下一个有效的方向,包括向上(你刚刚来自的方向) .
因为你在向下推动之前向上推到堆叠,当你到达你不能向下推的位置时,向上推动是最后一个位置,这意味着你将弹出向上位置并转到位置你来自哪里 .
从那里你会回来然后在无限循环中备份 .