Algorithm--Tower of Hanoi Problem

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right



提示:以下是本篇文章正文内容,下面案例可供参考

1. The Tower of Hanoi Problem

The Tower of Hanoi originates from an ancient legend in India. Brahma, the "God of Creation" of Hinduism, made three diamond pillars when he created the world. On one of the pillars, 64 gold discs were stacked in ascending order. Brahma ordered a disciple named Brahman to move all the disks to another pillar. The following rules must be observed during the movement process: only one disk at the
top of the pillar can be moved at a time;
on a large disc;

Moving n discs requires at least 2n-1 operations

Two, the code

1. Pseudocode

The code is as follows (example):

// num 表示移动圆盘的数量,source、target、auxiliary 分别表示起始柱、目标柱和辅助柱
hanoi(num , source , target , auxiliary): 
    if num == 1:     // 如果圆盘数量仅有 1 个,则直接从起始柱移动到目标柱
        print(从 source 移动到 target)
    else:
        // 递归调用 hanoi 函数,将 num-1 个圆盘从起始柱移动到辅助柱上,整个过程的实现可以借助目标柱
        hanoi(num-1 , source , auxiliary , target)
        // 将起始柱上剩余的最后一个大圆盘移动到目标柱上
        print(从 source 移动到 target) 
        // 递归调用 hanoi 函数,将辅助柱上的 num-1 圆盘移动到目标柱上,整个过程的实现可以借助起始柱               
        hanoi(n-1 , auxiliary , target , source)

2.c language

Kind of like a dichotomy.
The following is the pseudocode of the divide and conquer algorithm to find the maximum value in the array:

#include <stdio.h>
void hanoi(int num, char sou, char tar,char aux) {
    
    
    //统计移动次数
    static int i = 1;
    //如果圆盘数量仅有 1 个,则直接从起始柱移动到目标柱
    if (num == 1) {
    
    
        printf("第%d次:从 %c 移动至 %c\n", i, sou, tar);
        i++;
    }
    else {
    
    
        //递归调用 hanoi() 函数,将 num-1 个圆盘从起始柱移动到辅助柱上
        hanoi(num - 1, sou, aux, tar);
        //将起始柱上剩余的最后一个大圆盘移动到目标柱上
        printf("第%d次:从 %c 移动至 %c\n", i, sou, tar);
        i++;
        //递归调用 hanoi() 函数,将辅助柱上的 num-1 圆盘移动到目标柱上
        hanoi(num - 1, aux, tar, sou);
    }
}

int main()
{
    
    
    //以移动 3 个圆盘为例,起始柱、目标柱、辅助柱分别用 A、B、C 表示
    hanoi(3, 'A', 'B', 'C');
    return 0;
}

The data requested by the url network used here.


1st time: from A to B
2nd time: from A to C
3rd time: from B to C
4th time: from A to B
5th time: from C to A
6th time: from C moves to B
7th time: Moves from A to B

Summarize

For the Tower of Hanoi problem with n disks, the process of moving the disks is:
move the n-1 disks on the starting column to the auxiliary column;
move the remaining 1 disk on the starting column to the goal on the column;
move all discs on the auxiliary column to the target column.

Guess you like

Origin blog.csdn.net/lianghuajunone/article/details/123421284