我一直在编写一些代码来引导“机器人”通过具有多个死角的迷宫和 1 条通往目标的正确路径,如下所示:
我已经使用堆栈记录机器人第一次到达具有 3 或 4 个可能出口的正方形时所面对的方向,如果所有相邻的正方形都已被访问,则使用 pop() 使机器人从它首先返回的方向返回来自(与到达方向相反)。在运行结束时,堆栈包含到达目标路线上所有方格的方向。按照堆栈的相反方向将机器人从目标带回起点。我正在努力找出如何使用此堆栈,以便在下一次运行时机器人将采用最佳路径到达目标。
我的一些代码:
private int pollRun = 0; // Incremented after each pass
private int explorerMode; // 1 = explore, 0 = backtrack
public void exploreControl(IRobot robot) {
byte exits = nonwallExits(robot);
int direction;
switch (exits) { //passes control to respective method
case 1: direction = deadEnd(robot); break;
case 2: direction = corridor(robot); break;
case 3: direction = junction(robot); break;
default: direction = crossroads(robot); break;
}
if (exits == 1) {explorerMode = 0;}
robot.face(direction);
pollRun++;
}
public void backtrackControl(IRobot robot) {
byte exits = nonwallExits(robot);
int direction = IRobot.CENTRE;
switch (exits) { //passes control to respective method
case 1: direction = deadEnd(robot); break;
case 2: direction = corridor(robot); break;
default: direction = junction(robot); break; // do nothing
}
if (exits > 2) {
if (passageExits(robot) > 0){
exploreControl(robot);
explorerMode = 1;
pollRun++;
return;
} else {
robot.setHeading(st.pop());
robot.face(IRobot.BEHIND);
pollRun++;
return;
}
}
robot.face(direction);
pollRun++;
}
public void optimal(IRobot robot) {
byte exits = nonwallExits(robot);
int direction;
int heading;
for(int i = 0; i < st.size(); i++) {
stNew.push(st.pop());
}
if (exits < 3) {
switch (exits) { //passes control to respective method
case 1: direction = deadEnd(robot); break;
default: direction = corridor(robot); break;
}
robot.face(direction);
} else {
robot.setHeading(stNew.pop());
}
}
public void controlRobot(IRobot robot) {
if ((robot.getRuns() == 0) && (pollRun == 0)) {
robotData = new RobotData(); //reset the data store
explorerMode = 1;
}
if (robot.getRuns() = 1) {
optimal(robot);
return;
}
if (robot.getRuns() <= 0 && (nonwallExits(robot) >= 3)
&& (beenbeforeExits(robot) <= 0)) {
st.push(robot.getHeading());
}
if (explorerMode == 1) {
exploreControl(robot);
} else {backtrackControl(robot);}
}
最佳方法显示了我解决它的尝试,但它所做的只是让机器人在每个路口直行
比如这个迷宫,
会让我留下堆栈:东,东,南,南,东,南,南,东,东,南,南,东,东,东,南,东,南