迷宫回溯问题是指在一个设置了障碍的Map中,如何找到一条路径到达目标地点的问题,这个问题可以使用递归实现,但并不涉及最优解的求解,只要找到一条通路即可。
在这里,使用二维数据抽象代替Map,每个点有四种情况:0-该点未走过;1-该点为障碍;2-该点可走通;3-该点走过,但走不通;
1.生成一个指定大小的Map,保证外围都是1,模拟一个围墙,并手动设置随机的障碍,生成Map和设置障碍分别定义为两个方法。
package 迷宫回溯问题;
/**
* @Classname GenerateMap
* @Description:
* @Date 2022/6/16 15:03
* @Created by jiawen
*/
public class GenerateMap {
//Get a two-dimensional map which the size equals to rows*colums
public static int[][] getMap(int rows, int columns) {
int[][] map = new int[rows][columns];
for (int i = 0; i < rows; i++) {
map[i][0] = 1;
map[i][columns - 1] = 1;
}
for (int i = 0; i < columns; i++) {
map[0][i] = 1;
map[rows - 1][i] = 1;
}
return map;
}
public static void setBarriers(int[][] map, int x, int y) {
map[x][y] = 1;//map[x][y]被设置为障碍
}
}
2.主代码,用于在迷宫中寻找通路
package 迷宫回溯问题;
/**
* @Classname Maze
* @Description TODO
* @Date 2022/6/16 15:32
* @Created by jiawen
*/
public class Maze {
public static boolean backTracking(int[][] map, int currentRow, int currentColum) {
if (map[6][6] == 2) {//map[6][6]为手动设置的终点,等于2代表已经走到
return true;
} else {
if (map[currentRow][currentColum] == 0) {//未走过
map[currentRow][currentColum] = 2;
if (backTracking(map, currentRow - 1, currentColum)) {//尝试向上
return true;
} else if (backTracking(map, currentRow, currentColum + 1)) {//尝试向右
return true;
} else if (backTracking(map, currentRow + 1, currentColum)) {//尝试向下
return true;
} else if (backTracking(map, currentRow, currentColum - 1)) {//尝试向左
return true;
} else {
map[currentRow][currentColum] = 3;//走过但是走不通,溜了
return false;
}
} else {
return false;
}
}
}
public static void iteratorAll(int[][] map) {//打印地图
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + "\t");
}
System.out.println();
}
}
}
3.测试
package 迷宫回溯问题;
/**
* @Classname Solve
* @Description TODO
* @Date 2022/6/16 16:02
* @Created by jiawe
*/
public class Solve {
public static void main(String[] args) {
int[][] map = GenerateMap.getMap(8, 8);
GenerateMap.setBarriers(map, 3, 2);
GenerateMap.setBarriers(map, 2, 4);
GenerateMap.setBarriers(map, 5, 6);
GenerateMap.setBarriers(map, 4, 5);
Maze.backTracking(map, 1, 1);
Maze.iteratorAll(map);
}
}