所以我正在制作一个程序,它将以递归的方式解决迷宫,并且我的问题与我的问题有关 if else语句。我在我的代码的不同部分遇到了类似的问题,我通过取出所有其他的并且只是拥有一堆if语句来解决它。但现在我需要它找到正确的方法后停止搜索。
public static void solveMaze(int ROW, int COL){
int isFinished = 0;
//ROW COL
//set up base case. find end if possible to get in 1 move then end
if(drawArray[ROW][COL+1] == ' '){
if(drawArray[ROW][COL+2] == 'E'){
isFinished = 1;
move(ROW,COL,ROW,COL+2);
}
}
if(drawArray[ROW][COL-1] == ' '){
if(drawArray[ROW][COL-2] == 'E'){
isFinished = 1;
move(ROW,COL,ROW,COL-2);
}
}
if(drawArray[ROW+1][COL] == ' '){
if(drawArray[ROW+2][COL] == 'E'){
isFinished = 1;
move(ROW,COL,ROW+2,COL);
}
}
if(drawArray[ROW-1][COL] == ' '){
if(drawArray[ROW-2][COL] == 'E'){
isFinished = 1;
move(ROW,COL,ROW-2,COL);
}
}
//find first open cell and choose it
int foundOpen = 0;
if(isFinished == 0){
if(drawArray[ROW][COL+1] == ' ' && drawArray[ROW][COL+2] != '*'){
drawArray[ROW][COL+2] = '*';
prevCol = COL;
prevRow = ROW;
COL+= 2;
foundOpen = 1;
}
else if(drawArray[ROW+1][COL] == ' ' && drawArray[ROW+2][COL] != '*'){
drawArray[ROW+2][COL] = '*';
prevCol = COL;
prevRow = ROW;
ROW+= 2;
foundOpen = 1;
}
else if(drawArray[ROW][COL-1] == ' ' && drawArray[ROW][COL-2] != '*'){
drawArray[ROW][COL-2] = '*';
prevCol = COL;
prevRow = ROW;
ROW-= 2;
foundOpen = 1;
}
else if(drawArray[ROW-1][COL] == ' ' && drawArray[ROW-2][COL] != '*'){
drawArray[ROW-2][COL] = '*';
prevCol = COL;
prevRow = ROW;
ROW-= 2;
foundOpen = 1;
}
}
//i have two recursive voids so this is chosing between them
if(foundOpen == 1){
move(prevRow,prevCol,ROW,COL);
solveMaze(ROW,COL);}
else if (foundOpen == 0 && isFinished == 0)
wrongChoice(ROW, COL);
}
所以基本上这部分程序检查首先是否结束,如果它基本完成。我使用if else语句为第一部分,但我不会工作,我唯一能解决它的方法是取出其他的。所以在一个迷宫中,我必须解决第一步,应该是COL-1 ==''和COL-2!='*'。所以if语句应该发生,但它没有。我放入了一堆println语句来检查它的去向和isFInished == 0所以它开始进入if语句然后出现问题并且找不到任何解决方案,因此调用了wrongChoice。我是Java和递归的新手,所以我可能会遗漏一些obvios。
答案 0 :(得分:0)
您可以使用System.out.print并检查您希望它停止的位置,然后使用@mserioli建议,它将起作用。祝你好运
答案 1 :(得分:0)
boolean isFinished = true;
if (drawArray[ROW][COL+1] == ' ' && drawArray[ROW][COL+2] == 'E') {
move(ROW,COL,ROW,COL+2);
} else if (drawArray[ROW][COL-1] == ' ' && drawArray[ROW][COL-2] == 'E') {
move(ROW,COL,ROW,COL-2);
} else if (drawArray[ROW+1][COL] == ' ' && drawArray[ROW+2][COL] == 'E') {
move(ROW,COL,ROW+2,COL);
} else if (drawArray[ROW-1][COL] == ' ' && drawArray[ROW-2][COL] == 'E') {
move(ROW,COL,ROW-2,COL);
} else {
isFinished = false;
}
int foundOpen = 0;
if (!isFinished) {
应该这样做。
如果你经常这样看待naybors:
static final int[][] naybors = {
{ 0, 1 },
{ 0, -1 },
{ 1, 0 },
{ -1, 0 },
};
boolean isFinished = false;
for (int[] nb : naybors) {
if (drawArray[ROW + nb[0]][COL + nb[1]] == ' '
&& drawArray[ROW + 2*nb[0]][COL + 2*nb[1]] == 'E') {
move(ROW, COL, ROW + 2*nb[0], COL + 2*nb[1);
isFinished = true;
break;
}
}
还看到了:
else if(drawArray[ROW][COL-1] == ' ' && drawArray[ROW][COL-2] != '*'){
drawArray[ROW][COL-2] = '*';
prevCol = COL;
prevRow = ROW;
//Wrong: ROW-= 2;
COL -= 2; // Good?
foundOpen = 1;
}