Divide and Conquer Algorithm (Example of Towers of Hanoi)

This article has participated in the "Newcomer Creation Ceremony" event to start the road of gold creation together.

Introduction

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-S6JIhdIT-1647439879171) (C:\Users\Xu Zheng\AppData\Roaming\Typora\typora-user-images \image-20220316215349057.png)]

The basic idea of ​​the divide and conquer algorithm is to decompose a problem of size N into K smaller subproblems, which are independent of each other and have the same properties as the original problem. The solution to the original problem can be obtained by finding the solution to the subproblem. That is, a sub-objective completion program algorithm, simple problems can be completed by dichotomy.

The basic steps

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-ouYjMyd7-1647439879172) (C:\Users\Xu Zheng\AppData\Roaming\Typora\typora-user-images \image-20220316215525061.png)]

Design Patterns

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-kc3iKdwz-1647439879173) (C:\Users\Xu Zheng\AppData\Roaming\Typora\typora-user-images \image-20220316215612237.png)]

Algorithm Practice--Tower of Hanoi Problem

[External link image transfer failed, the origin site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-lzrYlzDb-1647439879173) (C:\Users\Xu Zheng\AppData\Roaming\Typora\typora-user-images \image-20220316215750937.png)]

Code

package com.xz.divideandconquer;

/**
 * @author 许正
 * @version 1.0
 */
public class HanoiTower {
    public static void main(String[] args) {
        hanoiTower(3, 'A', 'B', 'C');
    }

    //汉诺塔的移动的方法
    //使用分治算法
    public static void hanoiTower(int num, char a, char b, char c) {
        //如果只有一个盘
        if (num == 1) {
            System.out.println("第1个盘从 " + a + "->" + c);
        } else {
            //如果我们有 n >= 2 情况,我们总是可以看做是两个盘 1.最下边的一个盘 2. 上面的所有盘
            //1. 先把 最上面的所有盘 A->B, 移动过程会使用到 c
            hanoiTower(num - 1, a, c, b);
            //2. 把最下边的盘 A->C
            System.out.println("第" + num + "个盘从 " + a + "->" + c);
            //3. 把B塔的所有盘 从 B->C , 移动过程使用到 a塔
            hanoiTower(num - 1, b, a, c);
        }
    }
}
复制代码

Guess you like

Origin juejin.im/post/7085478128721592357