漢諾塔問題是使用遞歸解決問題的經(jīng)典范例。
漢諾(Hanoi)塔問題:古代有一個梵塔,塔內(nèi)有三個座A、B、C,A座上有64個盤子,盤子大小不等,大的在下,小的在上(如圖)。有一個和尚想把這64個盤子從A座移到B座,但每次只能允許移動一個盤子,并且在移動過程中,3個座上的盤子始終保持大盤在下,小盤在上。在移動過程中可以利用B座,要求打印移動的步驟。如果只有一個盤子,則不需要利用B座,直接將盤子從A移動到C。
#include <iostream>
#include <stdio.h>
using namespace std;
static int step = 0;
void move ( char sour, char dest )
{
printf ( "move from %c to %c \n", sour, dest );
}
void hanoi ( int n, char sour, char temp, char dest )
{
if ( n == 1 )
{
move ( sour, dest );
++step;
}
else
{
hanoi ( n-1, sour, dest, temp );
move ( sour,dest );
++step;
hanoi ( n-1, temp, sour, dest );
}
}
int main ( int argc, char **argv )
{
int n = 4;
hanoi ( n, 'A', 'B', 'C' );
printf ( "Total steps is %d\n", step );
return 0;
}