ALEXKK2011

The Technical Side of alexKK2011
  博客园  :: 新随笔  :: 订阅 订阅  :: 管理

Hanoi Problem (recursion)

Posted on 2011-02-17 12:36  alexkk2011  阅读(178)  评论(0编辑  收藏  举报
 
==================== Hanoi.h ========================
/*Hanoi.h
 * Hanoi class definition presents the public interface of the class.
 * Member-function definitions appear in Hanoi.cpp.
 */

// Hanoi class definition
class Hanoi
{
public :
    Hanoi(); // constructor that initializes a Hanoiobject
    ~Hanoi(); // 
    void HanoiMove(int, char [], char [], char []); // function that moves the Hanoi builds
    static int MoveCount; // count the number of movements
private:
    void MoveBlock(int, char [], char []);
};
 
==================== Hanoi.cpp ========================
//Hanoi.cpp
#include <iostream>
#include "Hanoi.h"

using namespace std;
//using namespace std::endl;

int Hanoi::MoveCount=0;
// constructor that initializes a Hanoi object
Hanoi::Hanoi(){}

Hanoi::~Hanoi(){}
// function that moves the block and print the process
// blockNum: the block number to be moved
// destiny: the column number to be reached
// from: move the block from which column
void Hanoi::MoveBlock(int blockNum, char destiny[], char from[])
{
    cout<<"Move block["<<blockNum<<"] from column<"<<from<<"> to column<"<<destiny<<">."<< endl;
    Hanoi::MoveCount++;
}
// function that moves the Hanoi blocks
// bottom: the bottom block number on the source column
// destiny: move the block to which column
// from: move the block from which column
// temp: the column serves as a temperate transportation
void Hanoi::HanoiMove(int bottom, char destiny[], char from[], char temp[])
{
    // there is only one block, then move it directly
    if(1==bottom)
    {
        MoveBlock(bottom, destiny, from);
        return;
    }
    // if there are only two blocks, then use the temp column
    else 
    {
        //--bottom: the second largest number of the blocks on the source column(move the sub-Hanoi (block[1]--block[n-1]) from source column to the temp column)
        HanoiMove(--bottom, temp, from, destiny);
        //++bottom: the number of the last block left on the source column
        MoveBlock(++bottom, destiny, from);
        //--bottom: the largest number of the blocks on the temp column
        HanoiMove(--bottom, destiny, temp, from);
    }
} 
void main()
{
    Hanoi han;
    char columnA[]="A";// destiny column
    char columnB[]="B";// temp column
    char columnC[]="C";// source column
    int end;
    cout<<"Please input the number of the blocks in the Hanoi(1,2,3...):";
    cin>>end;
    han.HanoiMove(end, columnA, columnC, columnB);
    cout<<"The number of total movements is :" << Hanoi::MoveCount << endl;
    return;
}