[Recursive] Tower of Hanoi game

Original title Portal

Thinking


This question card me an hour, is the first problem I encountered on CODEVS, do not peek solution to a problem, then probably really could not think of QAQ, it is really dish ah.

The main idea

A first order is to move to the Tower of Hanoi C
and n (n> 1) corresponds to the order HANOR performed three steps:
1. Perform the n-1 order HANOR shift method in the order of the ACB
2 from the A-> C maximum moving plate
3. Run the n-1 order HANOR shift method at the BAC sequence
is obvious, recursion finished.

Code


#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<stack>
using namespace std;

int n,k=1,i;

inline void move(int lv,char A,char C)
{
    cout<<lv<<" from "<<A<<" to "<<C<<endl;
}

void h(int lv,char A,char B,char C)
{
    if(lv==1)
        move(lv,A,C);
    else
    {
        h(lv-1,A,C,B);
        move(lv,A,C);
        h(lv-1,B,A,C);
    }
}

int main()
{
    cin>>n;
    for(i=1;i<=n;i++)k*=2;
    cout<<k-1<<endl;
    h(n,'A','B','C');
    return 0;
}

Guess you like

Origin www.cnblogs.com/gongdakai/p/11278464.html