[java]-Algorithms and Data Structures-Chapter 6-Recursion

6. Recursion

1. Concept

Recursion means that the method calls itself, passing in different variables each time it is called. Recursion helps programmers solve complex problems, and at the same time makes the code concise and
recursive – Baidu Encyclopedia

2. Recursive call mechanism

1) printing problem

    public static void test1(int n){
    
    
        if(n > 0){
    
    
            test1(--n);
        }
        System.out.println(n);
        return;
    }

2) Factorial problem

    public static int test2(int n) {
    
    
        if (n == 1) {
    
    
            return 1;
        } else {
    
    
            return test2(n - 1) * n; // 1 * 2 * 3
        }
    }

3. Important rules to follow for recursion

Important rules to follow for recursion:

  1. When a method is executed, a new protected independent space (stack space) is created
  2. The local variables of the method are independent and will not affect each other, such as n variables
  3. If a reference type variable (such as an array) is used in the method, the data of the reference type will be shared.
  4. The recursion must approach the condition of exiting the recursion, otherwise it will be an infinite recursion and a StackOverflowError will appear
  5. When a method finishes executing, or encounters a return, it will return, and whoever calls it will return the result to whomever it calls. At the same time, when the method finishes executing or returns, the method will also finish executing

4. The maze problem

insert image description here

Important rules to follow for recursion
Important rules to follow for recursion:

When executing a method, a new protected independent space (stack space) is created. The
local variables of the method are independent and will not affect each other. For example,
if the n variable is used in the method is a reference type variable (such as an array), it The data of this reference type will be shared.
The recursion must approach the condition for exiting the recursion, otherwise it will be infinite recursion. When a StackOverflowError occurs
when a method is executed, or when a return is encountered, it will return, and the caller will return the result to whomever follows. At the same time, when the method is executed or returned, the method is also executed

1) Code

public class Test02_迷宫 {
    
    

    public static void main(String[] args) {
    
    
        // 1. 创建二维数组模拟迷宫
        int[][] map = new int[8][7];
        // 2. 1表示墙
        for (int i = 0; i < map.length; i++) {
    
    
            for (int j = 0; j < map[i].length; j++) {
    
    
                if (i == 0 || i == 7) {
    
    
                    map[i][j] = 1;
                } else {
    
    
                    map[i][0] = 1;
                    map[i][6] = 1;
                }
            }
        }
        // 设置挡板
        map[3][1] = 1;
        map[3][2] = 1;

        for (int[] ints : map) {
    
    
            System.out.println(Arrays.toString(ints));
        }
        boolean b = setWay2(map, 1, 1);
        System.out.println("-------迷宫走完--------");
        for (int[] ints : map) {
    
    
            System.out.println(Arrays.toString(ints));
        }
    }

    // 使用递归给小球找路
    /*
     1. map 表示地图
     2. i,j 表示从地图的哪个位置开始触发
     3. 如果小球能到 map[6][5],说明小球出来了
     4. 约定:
        - 当map[i][j]为0,表示该点没有走过,当为 1表示墙,为2表示是通道. 3 表示已经探测过了但是,此路不通Z下
     5. 走迷哦给你个,确定一个策略 下 -》 右 -》 上 -》 左


    */
    public static boolean setWay(int[][] map, int i, int j) {
    
    
        if (map[6][5] == 2) {
    
    
            return true;
        } else {
    
    
            if (map[i][j] == 0) {
    
    
                // 当前节点还没有走过s
                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 {
    
    
                // map[i][j] != 0,可能是 1,2,3
                return false;
            }

        }
    }

    // 修改找路的策略,改成 上 -> 右 -> 下 -> 左
     public static boolean setWay2(int[][] map, int i, int j) {
    
    
        if (map[6][5] == 2) {
    
    
            return true;
        } else {
    
    
            if (map[i][j] == 0) {
    
    
                // 当前节点还没有走过s
                map[i][j] = 2;// 假设该点是可以走通的
                if (setWay2(map, i - 1, j)) {
    
    
                    // 向上走,
                    return true;
                } else if (setWay2(map, i, j+1)) {
    
    
                    // 向右走
                    return true;
                } else if (setWay2(map, i + 1, j)) {
    
    
                    // 向下走
                    return true;
                } else if (setWay2(map, i, j-1 )) {
    
    
                    // 向左走
                    return true;
                } else {
    
    
                    // 说明该点走不通
                    map[i][j] = 3;
                    return false;
                }
            } else {
    
    
                // map[i][j] != 0,可能是 1,2,3
                return false;
            }

        }
    }

    // 求出最短路径
}

5. Eight queens problem (backtracking algorithm)

1) Analysis of train of thought

  1. The first queen is first placed in the first row and first column
  2. The second queen is placed in the first column of the second row, and then judge whether it is OK. If not, continue to put it in the second column, the third column, and put all the columns in turn to find a suitable one.
  3. Continue to the third queen, or the first column, the second column... until the 8th queen can also be placed in a non-conflicting position, it is considered to have found a correct solution
  4. When a correct solution is obtained, when the stack rolls back to the previous stack, it will start backtracking, that is, the first queen and all the correct solutions in the first column will be obtained. 5. Then go back and continue with the first queen Put the second column, and then continue to execute steps 1, 2, 3, and 4 in a loop

Description: Use a one-dimensional array to build a chessboard, arr[8]={0,4,7,5,2,6,1,3}

  arr[i] = val;  val = 第 i+1 个皇后

2) Code

public class Test03_八皇后问题 {
    
    

    // 1. 定义一个 map 表示共有多少个皇后
    static int max = 8;
    // 2. 定义数组,皇后防止位置
    static int[] array = new int[max];

    // 3. 打印次数
    static int count = 0;
    public static void main(String[] args) {
    
    

        check(0);
        System.out.println(count);
//        print();

    }

    // 防止第 n 个皇后
    private static void check(int n){
    
    
        if(n == max){
    
    
            // 放到 第 8 个皇后,结束
            print();
            count++;
            return;
        }
        // 循环依次放入皇后,并且判断是否冲突
        for (int i = 0; i < max; i++) {
    
    
            // 1. 先把当前皇后n,放到改该行的第1列,
            array[n] = i;
            // 2. 放皇后放到 i列时,是否冲突
            if(judge(n)){
    
    
                // 3. 接着放 n+1 皇后,
                check(n+1);
            }
            // 3. 冲突 当前皇后向右移动。
        }
    }

    // 当我们防止第 n 个皇后时,检测该皇后是否和前面已经摆放的皇后是否冲突.
    private static boolean judge(int n){
    
    
        // n 表示 第 n 个皇后
        for (int i = 0; i < n; i++) {
    
    
            // 第二个计算 高度和宽度差  等腰∟三角形
            if(array[i] == array[n] || Math.abs(n-i) == Math.abs(array[n] -array[i])){
    
    
                // 两个皇后在同一列   两个皇后在同一斜线上
                return false;
            }
        }
        return true;
    }

    // 写一个方法,可以将最后结果
    private static void print(){
    
    
        System.out.println(Arrays.toString(array));
    }
}

Guess you like

Origin blog.csdn.net/m0_56186460/article/details/124225161