1 solutions
-
0
C :
#include <stdio.h> int count=0; void move(int disk,char start,char end) { printf("%d %c->%c\n",disk,start,end); ++count; return; } void hanoi(int n,char A,char B,char C) { if(n==1) move(1,A,C);//disk=1时,直接将disk从A移动到C else { hanoi(n-1,A,C,B);//第一步,将n-1个盘从A移动到B,其中C为辅助盘 move(n,A,C);//第二步,将n号盘直接从A移动到C hanoi(n-1,B,A,C);//第三步,将B盘上的n-1个盘递归调用 } return; } int main() { int disk_num; scanf("%d",&disk_num); hanoi(disk_num,'A','B','C'); printf("%d\n",count); return 0; }
C++ :
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<string> #include<algorithm> #include<iomanip> using namespace std; long long f=0; void han(int n,char a,char b,char c) { if (n==0) return; han(n-1,a,c,b); cout<<n<<" "<<a<<"->"<<c<<endl; han(n-1,b,a,c); f++; } int main() { //freopen("hanoi2.in","r",stdin); //freopen("hanoi2.out","w",stdout); int x; cin>>x; han(x,'A','B','C'); cout<<f; return 0; }
- 1
Information
- ID
- 637
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- (None)
- Tags
- # Submissions
- 0
- Accepted
- 0
- Uploaded By