考虑一个只能前进并向左或向右转的“机器人”。机器人在具有开放和封闭顶点的网格上行驶。机械手只能移动到开放顶点。它需要探索所有可能的开放顶点并返回到起始位置。
我一直试图将其实现为DFS,但由于某种原因无法使其正常工作。这是我到目前为止的内容(为清楚起见,省略了某些部分):
void DFS() {
switch (dir){
// int dir represents direction of robot, 0-east, 1-north,
// 2-west,3-south
// int visit[][] is an array that keeps track of cells visited
// int board[][] is the board on which the robot moves
// (element of board equals 1 if open, 0 if blocked).
// each time a move_forward() is called
// the robot either moves in its current direction
// or does not move, depending on the cell ahead (blocked or open)
case 0:
if (move_forward()==0){
if (visit[posx][posy+1]<1 && board[posx][posy+1]==OPEN){
turn_left();
} else if (visit[posx][posy-1]<1 && board[posx][posy-1]==OPEN ){
turn_right();
} else {
turn_right();
turn_right();
move_forward(); // This is where I try to make the
//robot start returning
}
break;
}
else
{DFS();}
case 1: ....
case 2: ....
case 3: .... // omitted cases are same as case 0, basically`
现在,此版本(如许多版本一样)无限递归。 我的问题是,我在做什么错? (或者,更好的是,我在做什么对吗?)我一直在尝试找出检查相邻顶点的方法,但是似乎没有任何事情会产生有意义的结果。我至少希望能够探索网格,然后集中精力将机器人退回。任何建议都欢迎,谢谢。