迷宮問題——遞歸
問題描述:
一個8行7列的迷宮四周是圍牆,從左上角的位置到達右下角,尋找一條軌跡
代碼:
package cn.littleworm;
//遞歸實現迷宮算法
public class Maze {
public static void main(String[] args) {
//創建二維數組,8行,7列
int[][] array = new int[8][7];
//四周是牆,用1來表示
for (int i = 0; i < 8; i++) {
array[i][0] = 1;
array[i][6] = 1;
}
for (int i=0;i<7;i++){
array[0][i] = 1;
array[7][i] = 1;
}
array[3][1] = 1;
array[3][2] = 1;
System.out.println("沒有進行找路之前:");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
// getWay(array,1,1);
// System.out.println("找路之後:");
// for (int i = 0; i < 8; i++) {
// for (int j = 0; j < 7; j++) {
// System.out.print(array[i][j]+" ");
// }
// System.out.println();
// }
getWay2(array,1,1);
System.out.println("找到路之後");
for (int i = 0;i<8;i++){
for (int j = 0;j<7;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
//創建出迷宮方法
/*
1、規定1爲牆,2爲已經走過的路,3爲不通的路,0爲沒有探索過的路
2、若map[6][5]爲2,則證明找到通路
3、出迷宮的策略:先下,在右,在上,後上
*/
//map爲地圖,i,j爲開始的位置
public static boolean getWay(int[][] map,int i,int j){
if (map[6][5]==2){ //如果map[6][5]爲2,證明找到出口
return true;
}else {
//判斷當前位置是否爲0;
if (map[i][j]==0){
//先將當前位置置爲2
map[i][j] = 2;
//根據策略進行向下尋找
//先向下找
if (getWay(map,i+1,j)){
return true;
}else if (getWay(map,i,j+1)){
return true;
}else if (getWay(map,i-1,j)){
return true;
}else if (getWay(map,i,j-1)){
return true;
}else {
map[i][j] = 3; //如果都沒有找到,那麼將這個位置置爲3,不通
return false;
}
}
//當前位置不爲0,那麼就是1,2,3,返回false
return false;
}
}
//getWay2採取的策略不同:採取上,右,下,左
public static boolean getWay2(int[][] map,int i,int j){
if (map[6][5]==2){ //如果map[6][5]爲2,證明找到出口
return true;
}else {
//判斷當前位置是否爲0;
if (map[i][j]==0){
//先將當前位置置爲2
map[i][j] = 2;
//根據策略進行向下尋找
//先向下找
if (getWay2(map,i-1,j)){
return true;
}else if (getWay2(map,i,j+1)){
return true;
}else if (getWay2(map,i+1,j)){
return true;
}else if (getWay2(map,i,j-1)){
return true;
}else {
map[i][j] = 3; //如果都沒有找到,那麼將這個位置置爲3,不通
return false;
}
}
//當前位置不爲0,那麼就是1,2,3,返回false
return false;
}
}
}
注:這裏面沒有使用圖形化界面,只是提供了邏輯代碼。並且這裏面也沒有使用算法實現最短路徑問題。這裏面只有通過更改小球尋找的策略來改變尋找軌跡
下,右,上,左策略
上,右,下,左的策略