Java implementation of recursive algorithm (Fibonacci sequence, Tower of Hanoi, N queen problem)

Java implementation of recursive algorithm (Fibonacci sequence, Tower of Hanoi, N queen problem)

Recursive definition

In mathematics and computer science, Recursion refers to the method of using the function itself in the definition of a function.

Three elements of recursion

1. Clarify the recursive termination conditions;

2. Give the processing method when the recursion terminates;

3. Extract the repetitive logic and reduce the scale of the problem.

Fibonacci sequence

The Fibonacci sequence (Fibonacci sequence), also known as the golden section sequence, was introduced because of the mathematician Leonardoda Fibonacci (Leonardoda Fibonacci) taking rabbit reproduction as an example, so it is also called the "Rabbit Sequence", referring to Is a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,... In mathematics, the Fibonacci sequence is defined by a recursive method as follows: F(0 )=0, F(1)=1, F(n)=F(n-1)+F(n-2) (n ≥ 2, n ∈ N*)

java code implementation

package 递归算法;

public class Fibonacci {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(fib(7));
    }

    /**
     * 
     * @param i 第i个元素
     * @return 返回第i个元素的值
     */
    private static int fib(int i) {
    
    
        if (i == 0 || i == 1){
    
    
            // 终止条件
            return i;
        }
        // 递归条件
        return fib(i - 1) + fib(i - 2);
    }
}


Tower of Hanoi

According to legend, there was a game called Hanoi in the ancient Indian temple. The game is on a copper plate device with three rods (numbered A, B, C). On the A rod, 64 gold plates are placed in order from bottom to top, from large to small (as shown in the figure below). The goal of the game: move all the gold discs on pole A to pole C, and stack them in the original order. Operating rules: Only one plate can be moved at a time, and the three rods always keep the big plate down and the small plate up during the movement. The plate can be placed on any of the rods A, B, and C during the operation.

java code implementation

package 递归算法;

public class Hanoi {
    
    
    public static void main(String[] args) {
    
    
        hanoi(3, "A", "B", "C");
    }

    /**
     *
     * @param i 层数
     * @param a 初始盘
     * @param b 借助盘
     * @param c 目标盘
     */
    private static void hanoi(int i, String a, String b, String c) {
    
    
        // 终止条件
        if (i == 1){
    
    
            move(1, a, c);
        }
        else{
    
    
            hanoi(i-1, a, c, b);
            move(i, a, c);
            hanoi(i-1, b, a, c);
        }
    }

    /**
     *
     * @param i 层数
     * @param a 初始盘
     * @param b 目标盘
     */
    private static void move(int i, String a, String b) {
    
    
        System.out.println(a + "-->" + b);
    }
}

N queen problem

The n queen problem studies how to place n queens on an n×n chessboard and make the queens unable to attack each other.
Eight Queens

java code implementation

package 递归算法;

import java.util.Scanner;

// 八皇后问题
public class NQueens {
    
    
    // 皇后个数
    private static int queen;
    // 计数
    private static int count = 0;
    // 定义一个棋盘
    static int[][] map;

    // 构造方法
    public NQueens(int queen){
    
    
        // 初始化皇后
        NQueens.queen = queen;
        // 初始化棋盘
        map = new int[queen][queen];
    }

    /**
     * 八皇后算法
     * @param row 表示行
     */
    public void play(int row){
    
    

        // 遍历当前行的所有单元格
        for(int i = 0; i < queen; i++){
    
    
            if (check(row, i)){
    
    
                map[row][i] = 1;
                if (row == queen-1){
    
    
                    show();
                } else {
    
    
                    play(row+1);
                }

                // 清空棋盘
                map[row][i] = 0;
            }
        }
    }

    /**
     * 显示棋盘的方法
     */
    public void show(){
    
    
        count++;
        System.out.println("第" + count + "种排列方式");
            for(int i = 0; i < queen; i++){
    
    
                for(int j = 0; j < queen; j++){
    
    
                    System.out.print(map[i][j] + " ");
                }
                System.out.println();
        }

    }

    /**
     * 检查是否可以放皇后
     * @param row 行
     * @param col 列
     * @return false不可以, true可以
     */
    private boolean check(int row, int col) {
    
    
        // 判断上面是否有皇后
        for(int i = row - 1; i >= 0; i--){
    
    
            if (map[i][col] == 1){
    
    
                return false;
            }
        }

        // 判左断斜上方是否有皇后
        for(int i = row -1, j = col - 1; i >= 0 && j >=0; i--, j--){
    
    
            if (map[i][j] == 1){
    
    
                return false;
            }
        }

        // 判断右斜上方是否后皇后
        for(int i = row -1, j = col + 1; i >= 0 && j < queen; i--, j++){
    
    
            if (map[i][j] == 1) {
    
    
                return false;
            }
        }
        return true;
    }



    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入皇后个数:");
        int queen = scanner.nextInt();
        NQueens queens = new NQueens(queen);
        queens.play(0);
    }

}

Guess you like

Origin blog.csdn.net/weixin_45017232/article/details/111291418