码迷,mamicode.com
首页 > 其他好文 > 详细

汉诺塔问题

时间:2015-04-04 12:17:57      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:c   算法   

问题:

         汉诺塔。

#include <stdio.h>
#include <stdlib.h>
void hanoi(int N, char A, char B, char C);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	int n;
	scanf("%d", &n);
	printf("the step to move %2d dishes are:\n", n);
	hanoi(n, 'A', 'B', 'C');
	return 0;
}

void hanoi(int N, char A, char B, char C)
{
	if(N==1)
		printf("move dish %d from %c to %c\n", N, A, C);
	else
	{
		hanoi(N-1, A, C, B);//A借助C将剩下的N-1个碟子转到B
		printf("move dish %d from %c to %c\n", N, A, C);
		hanoi(N-1, B, A, C);//B借助A将N-1个碟子转到C
	}
}
/*
5
the step to move  5 dishes are:
move dish 1 from A to C
move dish 2 from A to B
move dish 1 from C to B
move dish 3 from A to C
move dish 1 from B to A
move dish 2 from B to C
move dish 1 from A to C
move dish 4 from A to B
move dish 1 from C to B
move dish 2 from C to A
move dish 1 from B to A
move dish 3 from C to B
move dish 1 from A to C
move dish 2 from A to B
move dish 1 from C to B
move dish 5 from A to C
move dish 1 from B to A
move dish 2 from B to C
move dish 1 from A to C
move dish 3 from B to A
move dish 1 from C to B
move dish 2 from C to A
move dish 1 from B to A
move dish 4 from B to C
move dish 1 from A to C
move dish 2 from A to B
move dish 1 from C to B
move dish 3 from A to C
move dish 1 from B to A
move dish 2 from B to C
move dish 1 from A to C

--------------------------------
*/


汉诺塔问题

标签:c   算法   

原文地址:http://blog.csdn.net/orangeisnotapple/article/details/44871677

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!