hanoi 漢諾塔小遊戲編程寫步驟

#include<stdio.h>
int main()
{
void hanoi(int n, char one, char two, char three);ide

//聲明hanoi函數

int m;
printf("input the number of diskes:\n");
scanf("%d", &m); 函數

//輸入要移動盤的數目

printf("The step of move %d diskes\n", m);
hanoi(m, 'A', 'B', 'C'); code

//賦值給hanoi函數

system("pause");
}
void hanoi(int n, char one, char two ,char three) 遞歸

//定義hanoi函數

{
void move(char x, char y); three

//聲明move函數

if (n == 1) input

//遞歸函數的最後值

move(one, three); it

//賦值給move函數

elseio

//開始遞歸

{
hanoi(n - 1, one, three, two); class

//賦值給hanoi函數

move(one, three); 移動

//賦值給move函數

hanoi(n - 1, two, one, three);

//賦值給hanoi函數

//這個函數的意思能夠看作是:從上往下一共m個盤,

//將m-1個盤所有挪到two上,而後把m盤挪到three上,

//而後再將two上的全部盤挪到three上,就實現了。

//要挪m-1個盤在two上,必須把m-2個盤挪到three上,依次類推,層層遞歸。

}

//遞歸結束

}
void move(char x, char y) //定義move函數
{
printf("%c-->%c\n", x, y); //輸出每一步的指向
}

//這個hanoi的規律就是,單數的盤,第一個盤先個移向A,雙數的第一個盤盤則先移向B。

//移動次數=2^n-1。

相關文章
相關標籤/搜索