Recursively realize the maze path finding problem

Recursion: This method is called within a method, and a stack frame is created in the stack every time it is called, until the last method ends, the return starts, and the stack frames are popped out of the stack in turn.

This code realizes the idea 1. Define a maze and set the wall

2. Design your own walking method (down>right>up>left)

package MiGong;

//递归实现迷宫寻路问题
public class MiGongg {
    public static void main(String[] args) {
        int arr[][] = new int[8][7];
        arr[2][1]=1;
        arr[2][2]=1;
//        arr[2][3]=1;
//        arr[1][3]=1;
        for (int i=0;i<7;i++){
            arr[0][i] = 1;
            arr[7][i]=1;
        }
        for (int i=0;i<7;i++){
            arr[i][0] = 1;
            arr[i][6]=1;
        }
        for (int a[]:arr){
            for (int b:a){
                System.out.print(b+"\t");
            }
            System.out.println();
        }

        setWay(arr,1,1);

        System.out.println();
        for (int a[]:arr){
            for (int b:a){
                System.out.print(b+"\t");
            }
            System.out.println();
        }
    }

    public static boolean setWay(int arr[][],int i,int j){
        if (arr[6][5] == 2){
            return true;
        }else {
            if (arr[i][j] == 0){
                arr[i][j] =2;
                if (setWay(arr,i+1,j)){//向下走
                   return true;
               }else if (setWay(arr,i,j+1)){//向右走
                   return true;
               }else if (setWay(arr,i-1,j)){//向上走
                   return true;
               }else if (setWay(arr,i,j-1)){//向左走
                   return true;
               }else {//判断四个方向如果都走不通,则为死路
                    arr[i][j] =3;
                    return false;
                }
            }else {//如果map[i][j]不等零  则直接返回false
                return false;
            }
        }
    }
}

 

Guess you like

Origin blog.csdn.net/qq_41556688/article/details/113133284