代码:
#include<stdio.h>
void hanoi(int paraN, char paraSource, char paraDestination, char paraTransit)
{
if (paraN <= 0)
return;
else
{
hanoi(paraN - 1, paraSource, paraTransit, paraDestination);
printf("%c->%c\r\n", paraSource, paraDestination);
hanoi(paraN - 1, paraTransit, paraDestination, paraSource);
}
}
void hanoiTest()
{
printf("---hanoiTest begins---\r\n");
printf("2 plates\r\n");
hanoi(2, 'A', 'B', 'C');
printf("3 plates\r\n");
hanoi(3, 'A', 'B', 'C');
printf("---hanoiTest ends---\r\n");
}
void main()
{
hanoiTest();
}
结果:
图示:
时间复杂度为o(2^n); 空间复杂度为o(n)(可用栈的思想来理解,空间即内存)