迷宮回溯(遞歸Recursion)
public class Test {
// 迷宮回溯(遞歸Recursion)
// 1: wall, 2: can pass, 3: dead end(死路)
public static void main(String[] args) {
// first presents rows, second presents columns
int[][] map = new int[8][7];
// set walls to map(top row and bottom row)
for (int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1;
}
// the most left column and the most right column
for (int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}
map[3][1] = 1;
map[3][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();
}
}
/**
* 走迷宮策略:下 => 右 => 上 => 左
* @param map 地圖
* @param i 起點(列)
* @param j 起點(行)
* @return true此路可通 false此路不通
*/
public static boolean setWay(int[][] map, int i, int j) {
// set the end to return
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 {
// dead end
map[i][j] = 3;
return false;
}
} else {
// map[i][j] perhaps eqauls to 1,2,3
return false;
}
}
}
如有敘述錯誤,還請不吝嗇留言指教,thanks!