CSDN博客

img solotony

汉诺塔解法(C/C++)

发表于2004/7/17 15:34:00  1835人阅读

#include<iostream>
#include<string>

using namespace std;

void Hanoi(int n, string start, string middle, string end);

void move(int n, string start, string end)
{
    cout << "move:" << start << "->" << end << endl;
}

void exchange(int n, string start, string middle, string end)
{
    Hanoi(n - 1, start, end, middle);
    move(n, start, end);
    Hanoi(n - 1, middle, start, end);
}

void Hanoi(int n, string start, string middle, string end)
{
    return (n == 1) ? move(n, start, end) : exchange(n, start, middle, end);
}


int main(int argc, char** argv)
{
    int n;
    string start = "@", middle = "#", end = "$";

    n = argc > 1 ? atoi(argv[1]) : 3;
    cout << "The solution for n =" << n << endl;
    Hanoi(n, start, middle, end);

    return 0;
}

0 0

相关博文

我的热门文章

img
取 消
img