Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python

C++


JAVA
PHP
SQL
Assignments

Hanoi-Stack


solvehanoi.cpp

// solvehanoi.cc
//
// Charles A. Cusack, August 2000
//
// Show the solution to the Towers of Hanoi puzzle 
// with three towers given N discs.
// Usage:
// solvehanoi N
//
//-------------------------------------------------------------------------
#include "hanoi.h"
//-------------------------------------------------------------------------
void Solve_Hanoi(Hanoi &T,int N,int source,int destination,int spare);
//-------------------------------------------------------------------------
int main (int argc,char* argv[]) {

if(argc!=2 ) {       // Check for correct number of command line arguments.
    cout<<"USAGE: "<<argv[0]<<" number\n"; 
    exit(1); 
    }
int n=atoi(argv[1]);        // Convert input to int.

Hanoi Tower(n,3);           // Get the puzzle in it's start state.

Tower.Show_Towers();        // Show the initial state.

Solve_Hanoi(Tower,n,0,1,2); // Solve the puzzle.

return 0;
}
//-------------------------------------------------------------------------
void Solve_Hanoi(Hanoi &T,int N,int source,int destination,int spare) {
    if(N==1) {                                   // Base case. Do the move.
       if(!T.Move_Disc(source,destination)) 
         cout<<"Something went wrong.\n";           // Should not happen...
       T.Show_Towers();                     // Show the result of the move.
       }
    else {                              // Move the top N-1 discs to spare.
       Solve_Hanoi(T,N-1,source,spare,destination);
                                // Move the bottom disc to the destination.
       Solve_Hanoi(T,1,source,destination,spare);
                                  // Move the top N-1 discs to destination.
       Solve_Hanoi(T,N-1,spare,destination,source);
       }
    }
//-------------------------------------------------------------------------