/** * @Author: Yeman * @Date: 2021-10-28-22:52 * @Description: */ public class Labyrinth { public static void main(String[] args) { //七行八列的迷宫地图 int[][] map = new int[8][7]; //设置墙 for (int i = 0; i < 7; i++) { map[0][i] = 1; map[7][i] = 1; } for (int i = 0; i < 8; i++) { map[i][0] = 1; map[i][6] = 1; } map[2][1] = 1; map[2][2] = 1; //查看原地图 System.out.println("原地图:"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map[i][j] + " "); } System.out.println(); } //走迷宫 setWay(map, 1, 1); //查看走后的迷宫 System.out.println("走过的:"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map[i][j] + " "); } System.out.println(); } } //使用递归寻找 //约定0为还没走过,1为墙,2为通路,3为行不通的 public static boolean setWay(int[][] map, int i, int j){ if (map[6][5] == 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; } } } }