題目連結 http://zerojudge.tw/ShowProblem?problemid=a227。
以兩盤子個為例:
- 讓竿子一叫做 A,竿子二叫做B ,竿子三叫做C
 - 步驟一:從 A 移動 盤子1 到 B。
 - 步驟二:從 A 移動 盤子2 到 C。
 - 步驟三:從 B 移動 盤子1 到 C。
 
可看出規律:
- 從 A 移動 n-1個盤子 到 B。
 - 從 A 移動 第 n個盤子 到 C。
 - 從 B 移動 n-1個盤子 到 C。
 
程式碼:
#include <cstdio>
using namespace std;
void hanoi(int i, char from, char axu, char to)
{
 if(i == 1)
 {
  printf("Move ring %d from %c to %c\n", i, from, to);
 }
 else
 {
  hanoi(i-1, from, to, axu);
  printf("Move ring %d from %c to %c\n", i, from, to);
  hanoi(i-1, axu, from, to);
 }
}
int main(void)
{
 int n;
 while(scanf("%d", &n) == 1)
 {
  hanoi(n, 'A', 'B', 'C');
 }
}
沒有留言:
張貼留言