首页 > 试题广场 >

汉诺塔问题的打印

[编程题]汉诺塔问题的打印
  • 热度指数:857 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
打印n层汉诺塔从最左边移动到最右边的全部过程

输入描述:
输入一个大于0的正整数


输出描述:
n层汉诺塔从最左边移动到最右边的全部过程

示例1

输入

3

输出

Move 1 from left to right
Move 2 from left to mid
Move 1 from right to mid
Move 3 from left to right
Move 1 from mid to left
Move 2 from mid to right
Move 1 from left to right
#include <iostream>
using namespace std;

void Hanio(int n, string a, string b, string c){
    if(n == 1)
        cout << "Move 1 from " << a << " to " << c << endl;
    else{
        Hanio(n - 1, a, c, b);
        cout << "Move " << n << " from " << a << " to " << c << endl;
        Hanio(n - 1, b, a, c);
    }
}

int main() {
    int n;
    string a = "left";
    string b = "mid";
    string c = "right";
    cin >> n;
    Hanio(n, a, b, c);
    return 0;
}

编辑于 2024-01-06 10:26:25 回复(0)
#include <stdio.h>
#include <iostream>
using namespace std;

void move(int n, char* pos1, char* pos3)
{
    printf("Move %d from %s to %s\n", n, pos1, pos3);
}

void Hanoi(int n, char* pos1, char* pos2, char* pos3)
{
    //如果是1个盘子,直接从起始柱A移动到目标柱C
    if (n == 1) 
        move(n, pos1, pos3);
    else
    {
        //如果盘子大于1个,需要把n-1个盘子,从起始柱pos1,通过目标柱pos3,移动到中转柱pos2
        Hanoi(n-1, pos1, pos3, pos2); 
        //此时pos1上的n-1个盘子全部移动pos2上去了,那么可以直接把pos1上剩下的1个盘子,直接移动到pos3上
        move(n, pos1, pos3);
        //把pos2剩下的n-1个盘子,通过中转位置pos1,移动到目标位置pos3
        Hanoi(n-1, pos2, pos1, pos3);
    }
}

int main()
{
    int n;
    while(cin >> n)
    {
        char* pos1 = "left";
        char* pos2 = "mid";
        char* pos3 = "right";
        Hanoi(n, pos1, pos2, pos3);
    }
    return 0;
}

发表于 2022-01-15 09:31:30 回复(0)
#include <stdio.h>
#include <string.h>

void hanota(int n, char *A, char *B, char *C)
{
    if(1 == n) printf("Move %d from %s to %s\n", n, A, C);
    else
    {
        hanota(n-1, A,C,B);
        printf("Move %d from %s to %s\n", n, A, C);
        hanota(n-1, B,A,C);
    }
}

int main()
{
    int n;
    
    scanf("%d", &n);
    hanota(n,"left","mid","right");
    
    return 0;
}
发表于 2021-02-09 13:03:22 回复(0)

问题信息

上传者:小小
难度:
3条回答 1724浏览

热门推荐

通过挑战的用户