题解:
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cmath> 5 #include <cstring> 6 #include <vector> 7 #include <map> 8 #include <stack> 9 #include <queue> 10 #include <deque> 11 #include <list> 12 #include <set> 13 #include <cctype> 14 15 using namespace std; 16 17 inline int read(int &s) 18 { 19 s = 0; 20 int w = 1; 21 char ch = getchar(); 22 while (ch < '0' || ch > '9') 23 { 24 if (ch == '-') 25 w = -1; 26 ch = getchar(); 27 } 28 while (ch >= '0' && ch <= '9') 29 { 30 s = s * 10 + ch - '0'; 31 ch = getchar(); 32 } 33 return s * w; 34 } 35 36 inline void write(int x) 37 { 38 if (x < 0) 39 { 40 putchar('-'); 41 x = -x; 42 } 43 if (x > 9) 44 write(x / 10); 45 putchar(x % 10 + '0'); 46 } 47 48 void move(char A, char C, int n) 49 { 50 printf("%c->%c\n", A, C); // 把第n个圆盘从..移到.. 51 } 52 53 void hanoi(char A, char B, char C, int n) 54 { 55 if (n == 1) 56 move(A, C, n); 57 else 58 { 59 // 将n - 1个圆盘从A借助C移到B 60 hanoi(A, C, B, n - 1); 61 // 将A上的最后一个(第n个)移到C 62 move(A, C, n); 63 // 将n - 1个圆盘从B借助A移到C 64 hanoi(B, A, C, n - 1); 65 } 66 } 67 68 int main() 69 { 70 int n; 71 read(n); 72 hanoi('A', 'B', 'C', n); 73 return 0; 74 }
题解:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 void move(char a, char c, int n) 5 { 6 printf("%d:%c->%c\n", n, a, c); 7 } 8 9 void hanoi(char a, char b, char c, int n) 10 { 11 if (n == 1) 12 move(a, c, n); 13 else 14 { 15 hanoi(a, c, b, n - 1); 16 17 move(a, c, n); 18 19 hanoi(b, a, c, n - 1); 20 } 21 } 22 23 int main() 24 { 25 int n; 26 cin >> n; 27 char tmp; // 接受空格 28 char a, b, c; 29 tmp = getchar(); 30 a = getchar(); 31 tmp = getchar(); 32 b = getchar(); 33 tmp = getchar(); 34 c = getchar(); 35 tmp = getchar(); 36 37 hanoi(a, b, c, n); 38 39 return 0; 40 }
很经典的递归题目
标签:ch,int,hanoi,char,汉诺塔,include,getchar From: https://www.cnblogs.com/nijigasaki14/p/17529910.html