C language - the Tower of Hanoi step m

The m-th step of the Tower of Hanoi

Author: Turbo Time limit: 3S chapter: Recursive

Problem Description :

Given three different rods A, B, C, and the size of a few dishes. These plates set in descending order according to the size of the rod A, the smallest at the top. Now the task is to move the plate from the lever C A stacked bar and maintain the original order. In carrying out the task, a plate can only be moved, at any time and does not allow a large plate on the small plate above, B can be used as an auxiliary storage rod lever. Seeking: a total of n disks, the m-th step in the process of moving the rod from which the rod which is to.

Enter a description:

Your program needs from the standard input device (usually keyboard) reads multiple sets of test data. Each line of input data, each input line of a plate integer number n, 1≤n≤10, and the step number m, between two data separated by a space. Beginning of the line end of the line and no extra spaces, no extra blank line between the two sets of data.

Output Description:

For each test case, you need to program a standard output device (generally on the terminal program) corresponding to one line are sequentially outputted answer, the case where the m-th output line of the step movement, as in the first step is to move from A m B, the output "A-B" (without the quotes). If the m-th step movement does not exist, the output "none" (no quotes).

No blank line between two data sets, a first set of front and rear last group no blank lines.
Thinking:
Tower of Hanoi recursive main idea, when seeking the m-th step is used to set the global variable i and m i is determined the relationship, and with a flag Flag

#include <stdio.h>
int i=0,flag=-1;
void move(int m,char x,char y){
	i++;
	if(i==m){
		printf("%c--%c\n",x,y);	
		flag=1;
	}
			
}
int hanoi(int n,int m,char a,char b,char c){	
    if(n==1){
        move(m,a,c);//只有一个,A直接到C	
     }
    else{
        hanoi(n-1,m,a,c,b);//把A的n-1个盘子移到B
        move(m,a,c); //把最后一个盘子从A移到C
        
        hanoi(n-1,m,b,a,c);//把B柱n-1个盘子移到C
    }
}
int main(){
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF){
		hanoi(n,m,'A','B','C');
		if(flag==-1)
			printf("none\n");
		i=0;
		flag=-1;
	}
	return 0;
}

Here Insert Picture Description

Released eight original articles · won praise 6 · views 1409

Guess you like

Origin blog.csdn.net/weixin_44252790/article/details/104090071
Recommended