Lintcode227 Mock Hanoi Tower by Stacks solution 题解

【题目描述】

In the classic problem of Towers of Hanoi, you have 3 towers 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 (i.e., each disk sits on top of an even larger one). You have the following constraints:

Only one disk can be moved at a time.

A disk is slid off the top of one tower onto the next tower.

A disk can only be placed on the top of a larger disk.

Write a program to move the disks from the first tower to the last using stacks.

在经典的汉诺塔问题中,有 3 个塔和 N 个可用来堆砌成塔的不同大小的盘子。要求盘子必须按照从小到大的顺序从上往下堆 (如,任意一个盘子,其必须堆在比它大的盘子上面)。同时,你必须满足以下限制条件:

(1) 每次只能移动一个盘子。

(2) 每个盘子从堆的顶部被移动后,只能置放于下一个堆中。

(3) 每个盘子只能放在比它大的盘子上面。

请写一段程序,实现将第一个堆的盘子移动到最后一个堆中。

【题目链接】

www.lintcode.com/en/problem/mock-hanoi-tower-by-stacks/

【题目解析】

这是递归的经典题目。

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

将n个盘子从柱子src移动到柱子dst,其中可以借助柱子mid(middle 中间件)。既然要用到递归,当然是在这个函数中用到了函数本身.也就是说,我们在完成这个任务的步骤中还会用到haoni这个操作,只是参数可能不一样而已.

我们定义一个元组来表示三根柱子的状态:(src, mid, dst),数量为每根柱子上的圆盘数量:

初始状态: (n, 0, 0)

目标状态: (0, 0, n - 1)

中间状态: (n, n - 1, 0)

只有存在中间状态,才能将最大盘子n从src移动到dst,然后再将mid上的n-1个盘子移回到src上,这样问题规模就从n减少到n - 1了

从初始状态到中间状态使用操作 hanoi(src, dst, mid, n - 1)即可.即把n - 1个盘子从src移动到mid,中间借助dst。接下来,就是将圆盘n从src移动到dst即可 printf("Move disk %d from %c to %c", n, src, dst);

上面操作完成后,得到的状态是(0, n - 1, n),接下来,要将mid上的n - 1个盘子移动到dst上,用hanoi(mid, src, dst, n - 1)

【参考答案】

www.jiuzhang.com/solutions/mock-hanoi-tower-by-stacks/

你可能感兴趣的:(Lintcode227 Mock Hanoi Tower by Stacks solution 题解)