首页 > 代码库 > Hanoi塔问题(递归)

Hanoi塔问题(递归)

#include<iostream>#include<cstdio>using namespace std;int sum;int f(int n,char a,char b,char c){    if(n == 1){printf("1 from a to b\n");sum++;return sum;}    else {        f(n-1,a,c,b);        printf("%d from %c to %c\n",n,a,c);sum++;        f(n-1,b,a,c);    }}int main(){    int cases,  n;    cin>>cases;    while(cases--){        cin>>n;        sum = 0;        f(n,‘a‘,‘b‘,‘c‘);        printf("sum = %d\n",sum);    }    return 0;}

  

Hanoi塔问题(递归)