#1
by BlueRose » 6年前
n枚の円盤からなるハノイの塔のパズルを解くプログラムを再帰的プログラムで尚且つ円盤を移動する処理関数(honoi関数とする)を引数3つ(上からk枚の円盤, 始めに円盤が挿さっている棒from, 次の移動先の棒to)で実現するやり方のヒントを教えて下さい。
以下のコードは途中まで出来たものです。円盤の枚数は動的に当てはめていくので、棒from, toをどう定義していけばよいのか...。
コード:
#include <stdio.h>
/* プロトタイプ宣言 */
void hanoi(int, int, int);
/* メイン処理 */
int main(){
int n; //円盤の枚数
int from, to; //円盤が挿入されている棒、次の移動先の棒
printf("円盤の枚数 = ");
scanf("%d", &n);
hanoi(n, from, to);
return 0;
}
/* ハノイの塔を解く関数 */
void hanoi(int k, int from, int to){
int other; //from, to以外の棒
other = 6 - from - to;
if(k == 1){
printf("棒 from の 1 番上の円盤を棒 to へ移動\n");
}
if(k > 1){
hanoi(k-1, from, other);
}
if(k > 1){
hanoi(1, from, to);
printf("棒 %d から棒 %d へ移動\n", from, to);
}
if(k > 1){
hanoi(k-1, other, to);
}
}
n枚の円盤からなるハノイの塔のパズルを解くプログラムを再帰的プログラムで尚且つ円盤を移動する処理関数(honoi関数とする)を引数3つ(上からk枚の円盤, 始めに円盤が挿さっている棒from, 次の移動先の棒to)で実現するやり方のヒントを教えて下さい。
以下のコードは途中まで出来たものです。円盤の枚数は動的に当てはめていくので、棒from, toをどう定義していけばよいのか...。
[code]
#include <stdio.h>
/* プロトタイプ宣言 */
void hanoi(int, int, int);
/* メイン処理 */
int main(){
int n; //円盤の枚数
int from, to; //円盤が挿入されている棒、次の移動先の棒
printf("円盤の枚数 = ");
scanf("%d", &n);
hanoi(n, from, to);
return 0;
}
/* ハノイの塔を解く関数 */
void hanoi(int k, int from, int to){
int other; //from, to以外の棒
other = 6 - from - to;
if(k == 1){
printf("棒 from の 1 番上の円盤を棒 to へ移動\n");
}
if(k > 1){
hanoi(k-1, from, other);
}
if(k > 1){
hanoi(1, from, to);
printf("棒 %d から棒 %d へ移動\n", from, to);
}
if(k > 1){
hanoi(k-1, other, to);
}
}
[/code]