说明老鼠走迷宫是递回求解的基本题型,我们在二维阵列中使用2表示迷宫墙壁,使用1来表
示老鼠的行走路径,试以程式求出由入口至出口的路径。
解法老鼠的走法有上、左、下、右四个方向,在每前进一格之后就选一个方向前进,无法前进时退回选择下一个可前进方向,如此在阵列中依序测试四个方向,直到走到出口为止,这是递回的基本题,请直接看程式应就可以理解。
package test;
public class Mouse {
public static int[][] maze = {{2, 2, 2, 2, 2, 2, 2},
{2, 0, 0, 0, 0, 0, 2},
{2, 0, 2, 0, 2, 0, 2},
{2, 0, 0, 2, 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;
public static int startJ = 1;
public static int endI = 5;
public static int endJ = 5;
public static int success = 0;
public static void main(String[] args){
//将迷宫打印出来
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.print('n');
}
if(visit(startI,startJ)==0){
System.out.println("没有找到出口!");
}
else{
System.out.println("显示老鼠运动路径!");