Hanoi Tower问题分析

前言

回家休息第3天了,状态一直不是太好,主要是要补牙,检查身体,见同学见亲戚,心里又着急校招,难得能腾出时间来好好思考,这里也是看<cracking the coding interview>,看到了汉诺塔问题,这里记录一下

思路分析

汉诺塔是递归的经典题目,这里先介绍使用递归的关键:

使用递归的一个关键就是:我们先定义一个函数,不要着急去实现它,但是要明确它的功能

对于汉诺塔问题,我们定义如下函数原型:

void hanoi(char src, char mid, char dst, int n)

我们先不要在意它是如何实现的这种细节,而是先明确一下它的功能:

将n个盘子从柱子src移动到柱子dst,其中可以借助柱子mid(middle 中间件)

既然要用到递归,当然是在这个函数中用到了函数本身.也就是说,我们在完成这个任务的步骤中还会用到haoni这个操作,只是参数可能不一样而已.

我们定义一个元组来表示三根柱子的状态:(src, mid, dst),数量为每根柱子上的圆盘数量:
  1. 初始状态: (n, 0, 0)
  2. 目标状态: (0, 0, n - 1)
  3. 中间状态: (n, n - 1, 0)
只有存在中间状态,才能将最大盘子n从src移动到dst,然后再将mid上的n-1个盘子移回到src上,这样问题规模就从n减少到n - 1了

  1. 从初始状态到中间状态使用操作 hanoi(src, dst, mid, n - 1)即可.即把n - 1个盘子从src移动到mid,中间借助dst
  2. 接下来,就是将圆盘n从src移动到dst即可 printf("Move disk %d from %c to %c", n, src, dst);
  3. 上面操作完成后,得到的状态是(0, n - 1, n)
  4. 接下来,要将mid上的n - 1个盘子移动到dst上,用hanoi(mid, src, dst, n - 1)

递归代码

/**
 * In the classic problem of the Towers of Hanoi, you have 3 rods and  N disks of different
 * sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending
 * order of size from top to bottom. You have the following constraints:
 * (A) Only one disk can be moved at a time
 * (B) A disk is slid off the top of one rod onto the next rod
 * (C) A disk can only be placed on top of a larger disk
 * Write a program to move the disks from the first rod to the last using stacks
 */

#include <stdio.h>
#include <stdlib.h>

/**
 * 递归代码
 *
 * T = O(2^n - 1) 可推导证明
 *
 *
 */
void hanoi(char src, char mid, char dst, int n)
{
	if (n == 1) {
		printf("Move disk %d from %c to %c
", n, src, dst);
	} else {
		hanoi(src, dst, mid, n - 1);
		printf("Move disk %d from %c to %c
", n, src, dst);
		hanoi(mid, src, dst, n - 1);
	}
}


int main(void)
{
	int n;

	while (scanf("%d", &n) != EOF) {
		hanoi('A', 'B', 'C', n);
	}

	return 0;
}

参考链接

原文地址:https://www.cnblogs.com/pangblog/p/3246917.html