说明:老鼠走迷宫是递回求解的基本题型,我们在二维阵列中使用2表示迷宫墙壁,使用1来表示老鼠的行走路径,试以程式求出由入口至出口的路径。
解法:老鼠的走法有上、左、下、右四个方向,在每前进一格之后就选一个方向前进,无法前进时退回选择下一个可前进方向,如此在阵列中依序测试四个方向,直到走到出口为止,这是递回的基本题,请直接看程式应就可以理解。
public class mousemaze {
//迷宫初始化
public static int maze[][]= new int[][]{
{2,2,2,2,2,2,2},
{2,0,0,0,0,0,2},
{2,0,2,2,2,0,2},
{2,0,0,0,0,2,2},
{2,2,0,2,0,2,2},
{2,0,0,0,0,0,2},
{2,2,2,2,2,2,2}};
public static int startI=1,startJ=1;
public static int endI=5,endJ=5;
public static int success=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("显示迷宫");
for(int i=0;i<7;i++){
for(int j=0;j<7;j++){
if(maze[i][j]==2){
System.out.print("█");
}else{
System.out.print(" ");
}
}
System.out.println();
}
//
System.out.println("\n显示迷宫路线");
visit(startI,startJ);
}
public static void visit(int i,int j){
maze[i][j]=1;
if(i==endI&&j==endJ){
for(int a=0;a<7;a++){
for(int b=0;b<7;b++){
if(maze[a][b]==2){
System.out.print("█");
}else if(maze[a][b]==1){
System.out.print("*");
}else
System.out.print(" ");
}
System.out.print("\n");
}
}
if(maze[i][j+1]==0)visit(i,j+1);//右`这里写代码片`
if(maze[i+1][j]==0)visit(i+1,j);
if(maze[i][j-1]==0)visit(i,j-1);
if(maze[i-1][j]==0)visit(i-1,j);
maze[i][j]=0;
}
}