Detailed explanation of hanoi tower problem (divide and conquer + recursion)

        The Tower of Hanoi problem has always been a classic case for studying recursive algorithms, and it is also regarded as an advanced case of recursive algorithms by many textbooks. Today, we will take a look at the Tower of Hanoi problem!

First understand what is the Tower of Hanoi problem:

First, there are three pillars:

Start column (leftmost): source
Auxiliary column (rightmost): helper
Destination column (middle): dest 

There is a plate on the pillar. We move the left and right plates from small to large and stack them on the target pillar (middle pillar)

 The following is the movement action

 Then what we need to do is to write an algorithm, put the action of each movement in an array, let the algorithm calculate how to move to achieve the goal, first look at the result

 look at this

      Array, can you clearly see how it goes? Even if there are 100 plates, you can quickly calculate how to go, just follow the steps above the array. 

Now that we know our goal, let’s write the code together

 I'll show the code first, then explain

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    /** 
 * @param {圆盘数:number} plates 
 * @param {起始柱子 a:string} source 
 * @param {辅助柱子 b:string} helper 
 * @param {目标柱子 c:string} dest 
 * @param {移动步骤集:Array,数组的长度就是移动的次数} moves 
 */
    var move1 = []
    function hanoi(plates, source, helper, dest, moves = []) {
        if (plates <= 0) {
            return moves;
        }
        if (plates === 1) {
            moves.push([source, dest]);
            move1.push([source, dest, helper]);
        } else {
            hanoi(plates - 1, source, dest, helper, moves);
            moves.push([source, dest]);
            hanoi(plates - 1, helper, source, dest, moves);
        }
        return moves;
    }

    // test
    console.log(hanoi(5, 'source', 'helper', 'dest')); // 输出结果如下图展示
</script>
</html>

 The most difficult thing is the two recursive calls in the else. This is not easy to explain. I made a picture to help understand!

 

The Tower of Hanoi on the 5th floor is too big, so it is not easy to take a screenshot. I put a 4th floor. In fact, the principle is the same. 

The 4th floor is 2 to the fourth power -1, which is 15 times;

The 5th floor is 2 to the 5th power -1, and 31 times are obtained;


 

This is not easy to understand, and it takes time. I worked on it all night and then drew the picture. If you are interested, you can private me and discuss it together. If there is something wrong, you are welcome to guide!

Guess you like

Origin blog.csdn.net/fightingLKP/article/details/126254841