A brief description of java recursion to realize the mouse out of the maze

Table of contents

1. Maze map

Code:

Map effect:

 2. Walk the maze

Code:

Code effect:


1. Maze map

We print the maze map using a two-dimensional array, 1 for obstacles and 0 for no obstacles.

Code:

int map[][] = new int[8][7];
		for(int i = 0 ; i< 7; i++){ 
				map[0][i]=1;//1表示障碍物
				map[7][i]=1;
		}
		//打印第一列和最后一列的障碍物
		for(int i = 0 ; i< 8 ; i++){
			map[i][0] = 1;
			map[i][6] = 1;

		}
		map[3][2]=1;//具体的障碍点设置
		map[3][1]=1;

		System.out.println("===地图===");
		for(int i = 0 ; i< map.length ; i++){
			for(int j=0 ;j < map[i].length; j++){
				System.out.print(map[i][j] + " " );
			}
			System.out.println();//每输出一行后就换行
		}

Map effect:

 2. Walk the maze

We assume: 0 means that there is no obstacle, 1 means that there is an obstacle, 2 means that the hypothesis can go, and 3 means that you can go but can't go.

Returns true if a way out is found, false if not found

Idea: Create a method findway to find the way. When we use recursion, write the recursion end condition in front of the program. If the mouse is at the exit position of the array, the array element is equal to 2, then return true. The path finding is completed. If there are no obstacles, we assume that the position is 2, and then use recursion to go up, down, left, and right. If you can walk, return true. If you can walk but cannot go, assign a value of 3 and return false. .

Code:

//0表示没有障碍物   1表示障碍物  2 表示假设可以走  3 表示可以走但是走不通
//如果找到出路 返回true 没有找到 返回false
class M{
	public boolean findway(int map[][],int i,int j){//实现找路功能
		if(map[6][5]==2){
			return true;
			//递归结束条件  当小老鼠走到出口时结束递归
		}else {
			if(map[i][j] == 0){//如果当前位置没有障碍物
				map[i][j] = 2;//0表示没有障碍物可以走
				if(findway(map , i+1 ,j)){//下
					return true;
				}else if(findway(map , i ,j+1)){//右
					return true;//下
				}else if(findway(map , i-1 ,j-1)){//上
					return true;
				}else if(findway(map , i , j-1)){//左
					return true;
				}else{
					map[i][j]=3;//3表示能走但是走不通
					return false;
				}
			}else{
				return false;
			}

		}

	}
}


Code effect:

 We estimate what will happen if we block the surrounding area of ​​the initial position of the little mouse and see what will happen. If there is no accident, 3 should be generated. The little mouse used a little bit of backtracking to walk the maze.

Guess you like

Origin blog.csdn.net/weixin_64131583/article/details/123107202