我需要帮助我的代码,以便我可以从起点穿过迷宫并打印出每一步 这里的代码将遍历迷宫
public boolean solveMaze(int row, int col){
boolean done = false;
if (valid(row, col)) {
if(MazeArr[row][col] =='E')
done = true; // the maze is solved
else {
done = solveMaze(row+1, col); // down
if (!done)
done = solveMaze(row, col+1); // right
if (!done)
done = solveMaze(row-1, col); // up
if (!done)
done = solveMaze(row, col-1); // left
if(!done)
done= backtrack(row,col); //backtracks
}
if (done) // this location is part of the final path
MazeArr[row][col] = PATH;
}
return done;
}
这个检查索引是否有效 private boolean valid(int row,int column)
{ boolean result = false;
// check if cell is in the bounds of the matrix
if (row >= 0 && row < MazeArr.length &&column >= 0 &&
column <MazeArr[row].length)
// check if cell is not blocked and not previously tried
if (MazeArr[row][column] ==' '|| MazeArr[row][column] =='E')
result = true;
return result; }
只要迷宫到达死胡同,这个就会回溯
//backtracks the trace
public boolean backtrack(int row, int col){
boolean checkpoint=true;
DLLBasedStack<Integer> stackRow = new DLLBasedStack<>();
DLLBasedStack<Integer> stackCol = new DLLBasedStack<>();
if ((MazeArr[row+1][col]==' ' && MazeArr[row-1][col]==' ')|| (MazeArr[row][col+1]==' ' && MazeArr[row][col-1]==' ')|| MazeArr[row][col]=='S')
checkpoint=false;
stackRow.push(row);
stackCol.push(col);
int r=stackRow.pop();
int c= stackRow.pop();
if(!valid(row,col))
checkpoint=true;
solveMaze(r,c);
returncheckpoint;
}