69,374
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#define N 10
typedef struct hanoi{
int n;
char a ; char b ; char c ;
} hanoi ;
hanoi p[N+1];
int top = 1;
int count = 0;
void push( hanoi p[] , int n, char a, char b, char c){
p[top].n = n;
p[top].a = a;
p[top].b = b;
p[top].c = c;
top ++ ;
}
void not_recur_hanoi(int n){ // n = [1,N] n is the number of disk
char a = 'A' , b = 'B' , c = 'C' ;
push( p , n , a , b , c);
for( ; top > 1 ; ){ // not void
for( ; p[top-1].n > 1 ; ) {
push( p , p[top-1].n - 1 , p[top-1].a , p[top-1].c , p[top-1].b) ;
}
printf( " move disk %d from %c to %c \n",
p[top-1].n , p[top-1].a , p[top-1].c ); // 顶为1,底为n
count ++ ;
top -- ;
if( top > 1){
printf( " move disk %d from %c to %c \n",
p[top-1].n , p[top-1].a , p[top-1].c );
count ++ ;
char temp_a = p[top-1].a , temp_b = p[top-1].b ,temp_c = p[top-1].c,
temp_n = p[top-1].n;
top -- ;
push ( p, temp_n - 1 , temp_b , temp_a , temp_c);
}
}
}
int main(){
not_recur_hanoi( 4 ); // must be less than N
printf("the number of movement is %d " , count) ;
return 0;
}
#include <stdio.h>
void hanoi(int n,char one,char two,char three);
void move(char x,char y);
int main(void)
{
int n;
printf("input the number of diskes:");
scanf("%d",&n);
printf("The step to moving %d diskes:\n",n);
hanoi(n,'A','B','C');
return 0;
}
void hanoi(int n,char one,char two,char three)
{
if(n==1)
move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}