package com.object.experiment04;
/*老鼠迷宫问题*/
public class MouseMaze<or> {
public static void main(String[] args) {
//定义一个二位数组
int[][] mouse = new int[10][10];
//给二维数组的最上最右最左最右行赋值(0表示可以走,1表示不可以走)
for ( int i = 0; i < 10; i++ ) {
//最上最下行赋值
mouse[0][i] = 1 ;
mouse[9][i] = 1 ;
//最左最右行赋值
mouse[i][0] = 1 ;
mouse[i][9] = 1;
}
//手动设置障碍
mouse[3][3] = 1 ;
mouse[2][3] = 1 ;
mouse[4][4] = 1 ;
mouse[3][2] = 1 ;
mouse[3][1] = 1 ;
mouse[3][4] = 1 ;
//输出迷宫模型(输出二维数组)(增强for循环)
for (int[] one : mouse) {
for (int two : one) {
System.out.print("\t"+two);
}
System.out.println();
}
//调用方法让老鼠走出迷宫(mouse[9][9] == 2时,为走出迷宫)
boolean mouseSuccess = findMouse(mouse, 1, 1);
//判断是否走出迷宫
if (mouseSuccess==true){
System.out.println("老鼠成功走出迷宫");
}else {
System.out.println("此迷宫为死迷宫");
}
//输出成功或者迷宫(输出二维数组)(增强for循环)
for (int[] one : mouse) {
for (int two : one) {
System.out.print("\t"+two);
}
System.out.println();
}
}
private static boolean findMouse(int[][] mouse, int x, int y ) {
//当坐标为(X,Y)=2;时表示可以通过
//当mouse[8][8] == 2时表示通关
if (mouse[8][8] == 2 ){
return true;
}else if (mouse[x][y] == 0){//表示还可以通过
//此时假定迷宫可以走
mouse[x][y] = 2;
if (findMouse(mouse,x+1,y)){//先向下走
return true;
}else if (findMouse(mouse,x,y+1)){//向右走
return true;
}else if (findMouse(mouse,x-1,y)){//向上走
return true;
}else if (findMouse(mouse,x,y-1)){//向左走
return true;
}else{
mouse[x][y] = 3 ;
return false;
}
}else{//表示不可以走
return false;
}
}
}