百度百科:
汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
设三根柱子,A,B,C.
当盘数为1时,
A1->C
当盘数为2时,
A1->B
A2->C
B1->C
当盘数为3时,
A1->C
A2->B
C1->B
A3->C
B1->A
B2->C
A1->C
归纳法:
当盘数为n时:
A的(n-1)个盘->B
An->C
B的(n-1)个盘->C
此时,可用递归解决问题
public class Test {
public int count = 0;
public static void main(String[] args) {
Test t = new Test();
t.hanoi(4, 'A', 'B', 'C');
System.out.println("Total: " + t.count);
}
public void hanoi(int n,char A,char B,char C){
if(n == 1){
++count;
System.out.println((char)A + " " + n + " -> " + C);
}else{
hanoi(n-1,A,C,B);
++count;
System.out.println((char)A + " " + n + " -> " + C);
hanoi(n-1,B,A,C);
}
}
}
#include <iostream>
using namespace std;
void hanoi(int n,char A,char B,char C);
int count = 0;
int main()
{
hanoi(4,'A','B','C');
cout << "Total: " << count << endl;
return 0;
}
void hanoi(int n,char A,char B,char C)
{
if(n == 1)
{
++count;
cout << A << " " << n << " -> " << C << endl;
}
else
{
hanoi(n-1,A,C,B);
++count;
cout << A << " " << n << " -> " << C << endl;
hanoi(n-1,B,A,C);
}
}