我正在学习有关c++中的递归的信息,但是被以下用于解决河内塔问题的c++代码所困扰。
void Hanoi(int m, string start, string middle, string end){
cout << "m is equal to: " << m << endl;
if(m == 1){
cout << "Move Disc " << " from " << start << " to " << end << endl;
}
else{
Hanoi(m-1,start,end,middle);
cout << "Move disc " << m << " from " << start << " to " << end << endl;
Hanoi(m-1,middle,start,end);
}
}
int main(){
int discs = 3;
Hanoi(discs, "start","middle","end");
}
代码的输出如下:
m is equal to: 3
m is equal to: 2
m is equal to: 1
Move Disc from start to end
Move disc 2 from start to middle
m is equal to: 1
Move Disc from end to middle
Move disc 3 from start to end
m is equal to: 2
m is equal to: 1
Move Disc from middle to start
Move disc 2 from middle to end
m is equal to: 1
Move Disc from start to end
我的一般问题是我不了解递归的工作方式。为什么在执行“if”语句之前将m设为1? m如何回到2?
最佳答案
如果将其打印为树,则会得到以下内容:
main
|--> hanoi(3, ...)
| |
| |--> hanoi(2, ...)
| | |
| | |--> hanoi(1, ...)
| | |--> hanoi(1, ...)
| |<----|
| |--> hanoi(2, ...)
| | |
| | |--> hanoi(1, ...)
| | |--> hanoi(1, ...)
| |<----|
|<-----|
|
对于
hanoi(m, ...)
的每次调用,除非m == 1,否则它将两次调用hanoi(m-1,...)...在第一个调用中,它将再次调用hanoi(m-1,...)...直到m是1。因此,当m为2时向后走,它将连续两次调用hanoi(1,...):
hanoi(2, ...)
hanoi(1, ...)
hanoi(1, ...)
当m为3时,它将连续两次调用hanoi(2,...),因此:
hanoi(3, ...)
hanoi(2, ...)
hanoi(1, ...)
hanoi(1, ...)
hanoi(2, ...)
hanoi(1, ...)
hanoi(1, ...)