弄了半天,灵魂递归算法:
代数是这样描述的(大抵是这样说的):
当n==1时,有固定值。
当func(k)时,可以得到 func(k+1)时便可用递归。
汉洛塔:假设我知道怎么移动 n-1层,那我也知道怎么移动n层了。
#include<iostream> using namespace std; void moveDisk(int n, char from, char to, char tmp); int main(){ moveDisk(6, 'A', 'C', 'B'); int a; cin >> a; return 1; } //123456 void moveDisk(int n, char from, char to, char tmp){ if (n == 1){ cout << "move disk"<<n<<" from " << from <<" to "<<to<< endl; } else{ moveDisk(n - 1, from, tmp, to); cout << "move disk" << n << " from " << from << " to " << to << endl; moveDisk(n - 1, tmp, to, from); } }