1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
int num_moves_non_adjacent( int num_disks )
{
// http://appsrv.cse.cuhk.edu.hk/~chi/csc2110-2009/notes/T10.pdf
if( num_disks == 1 ) return 2 ;
else return 3 * num_moves_non_adjacent( num_disks-1 ) + 2 ;
}
// invariant: towers are numbered 1, 2, 3 see line 23: 'may be commented out if...'
// bool is_adjacent( int tower_a, int tower_b ) { return tower_a == 2 || tower_b == 2 ; }
int move_number = 0 ;
void move_one( int disc, int source, int dest )
{
std::cout << ++move_number << ". move disc #" << disc << " from peg " << source
<< " to peg " << dest << '\n' ;
}
void hanoi( int diskSize, int source = 1, int dest = 3, int spare = 2 )
{
/*////////// may be commented out if it is guaranteed that /////////////////////////
//////////// initially, source and dest are not adjacent; because then, ///////////////
//////////// none of the recursive calls will ever be for adjacent pegs ///////////////
if( is_adjacent( source, dest ) )
{
if( diskSize == 0 ) move_one( 0, source, dest ) ;
else
{
hanoi( diskSize-1, source, spare, dest ) ;
move_one( diskSize, source, dest ) ;
hanoi( diskSize-1, spare, dest, source ) ;
}
}
else
*//////////////////////////////////////////////////////////////////////////////////////////////
{
if( diskSize == 0 )
{
move_one( 0, source, spare ) ;
move_one( 0, spare, dest ) ;
}
else
{
hanoi( diskSize-1, source, dest, spare ) ;
move_one( diskSize, source, spare ) ;
hanoi( diskSize-1, dest, source, spare ) ;
move_one( diskSize, spare, dest ) ;
hanoi( diskSize-1, source, dest, spare ) ;
}
}
}
| |