明确问题
1. 明确地图的那个位置开始出发(1,1)
2. 明确走到那个位置,表示通路找到
3. 明确走迷宫时候的策略:下 —> 右 —> 上 —> 左。
4. 约定:0表示没走过的点,1表示墙,2表示通路可以走,3表示该点已经走过,但是走不通。
package com.liang.recursion;
import java.util.Random;
public class Maze {
public static void main(String[] args) {
int[][] map = createMap(20, 20);
System.out.println("打印地图情况");
for (int i = 0; i < map.length; i++){
for (int j = 0; j < map[0].length; j++){
System.out.print(map[i][j]+" ");
}
System.out.println();
}
System.out.println("---------------------------");
setWay(map,1,1);
System.out.println("走过的路线");
for (int i = 0; i < map.length; i++){
for (int j = 0; j < map[0].length; j++){
System.out.print(map[i][j]+" ");
}
System.out.println();
}
}
public static int[][] createMap(int row,int column){
int[][] map = new int[row][column];
for (int i = 0; i < column; i++){
map[0][i] = 1;
map[row-1][i] = 1;
}
for (int i = 0; i < row; i++){
map[i][0] = 1;
map[i][column-1] = 1;
}
int n = (row > column ? column : row);
Random random = new Random();
for (int i =0; i < n; i++ ){
map[random.nextInt(n)][random.nextInt(n)] = 1;
}
return map;
}
public static boolean setWay(int[][] map, int i,int j){
if(map[map.length-2][map[0].length-2] == 2){
return true;
}else{
if(map[i][j] == 0){
map[i][j] = 2;
if (setWay(map,i+1,j)){
return true;
}else if(setWay(map,i,j+1)){
return true;
}else if (setWay(map,i-1,j)){
return true;
}else if(setWay(map,i,j-1)){
return true;
}else {
map[i][j] = 3;
return false;
}
}else {
return false;
}
}
}
}