首页 > 代码库 > 老鼠走迷官java实现

老鼠走迷官java实现

老鼠走迷宫是递回求解的基本题型,我们在二维阵列中使用2表示迷宫墙壁,使用1来表示老鼠的行走路径,试以程式求出由入口至出口的路径。



public class MouseAlt {
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,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}
};
/**
* @param args
*/
static int startI = 1; 
static int startJ = 1;
static int endI = 5; 
static int endJ = 5;
static int success = 0;
public static void main(String[] args) {
System.out.println("显示迷宫:\n");
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();
}

if(visit(startI, startJ) ==0) {
System.out.println("没有找到出口");
} else {
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 if(maze[i][j] == 1) {
System.out.print("◇ ");
}else {
System.out.print("* ");
}
}
System.out.println();
}
}
}


public static int visit(int i, int j) {
maze[i][j] = 1;
if(i == endI && j == endJ) {
success = 1;
}
if(success != 1 && maze[i][j+1] == 0) visit(i, j+1);
if(success != 1 && maze[i+1][j] == 0) visit(i+1,j);
if(success != 1 && maze[i][j-1] == 0) visit(i, j-1);
if(success != 1 && maze[i-1][j] == 0) visit(i-1,j);
if(success != 1)
maze[i][j] = 0;
return success;
}
}


老鼠走迷官java实现