Hanoi Tower: 经典的BFS(宽度广度优先搜索)再演绎
这是TopCoder SRM 446的1000分题目,关于著名的汉诺塔(Hanoi Tower)的变形及其解法。应该说,这道题比基本的汉诺塔要难很多,特别是要求求出最优解。因此,相对于常用的递归或DFS深度优先搜索策略来说,在这里,需要用BFS广度优先搜索结合动态规划的解法。同时,本文给出了有关其最佳数据结构的讨论。
TopCoder SRM 446 1000-Point Problem - HanoiTowerProblem Statement | |||||||||||||
In this problem we consider a modification of the classical Hanoi Towers game. The rules of our modification are as follows:
The initial locations of the discs are given in the strings pegA, pegB and pegC. Each character of pegA represents a disc located on peg A, where 'A' represents a disc of type A, 'B' represents a disc of type B and 'C' represents a disc of type C. The discs are given in order, from bottom to top. pegB and pegC describe the discs on pegs B and C, respectively, in the same format. Return the minimum number of moves required to achieve the goal of the game. | |||||||||||||
Definition | |||||||||||||
| |||||||||||||
Notes | |||||||||||||
- | It's always possible to achieve the goal of the game. | ||||||||||||
Constraints | |||||||||||||
- | pegA, pegB and pegC will contain only the characters 'A', 'B' and 'C'. | ||||||||||||
- | The total number of characters in pegA, pegB and pegC will be between 1 and 10, inclusive. | ||||||||||||
Examples | |||||||||||||
0) | |||||||||||||
| |||||||||||||
1) | |||||||||||||
| |||||||||||||
2) | |||||||||||||
| |||||||||||||
3) | |||||||||||||
| |||||||||||||
4) | |||||||||||||
|
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
汉诺塔问题,是一个经典的递归算法案例。这道题继承了汉诺塔的特点,同时特殊的修改使其比普通的汉诺塔问题更具有挑战性。递归问题大多可用动态规划结合BFS(广度优先搜索,又称宽度优先搜索)的算法,这道题也一样,解答步骤为:
1、对于每一个状态(pegA, pegB, pegC),由于要寻找其解,放入当前步骤(搜索层)问题表(队列堆栈皆可)。最开始初始化时表中只有一个元素,即最初状态。(这里看到有些选手采用优先级队列,那样的话STL底层维护起来很麻烦,其实只要用BFS就没有必要用优先级队列)
2、维护一个搜索集set。对于状态(pegA, pegB, pegC),如果已在搜索中,则该分支陷入重复,放弃该分支搜索;否则加入搜索集。(一般set无需判断,直接insert即可)
3、遍历当前问题表求解。如果有某一状态满足终止条件,那么当前步骤数即为所求,返回;如果没有,则展开得到更深层次的问题表,步骤数++。返回步骤1。
注意:建议对“状态(pegA, pegB, pegC)”进行优化,最好将其计算为一个数字。如本题可以采用一个“三进制数”表达一个peg。看到有些选手直接用string[3]来代表这个状态,复杂度比较高,不过TC系统测试也能通过。
由于比赛完已经很晚了,稍微描述了一下思路,希望能对感兴趣的朋友一些参考和帮助。也欢迎你们留言发表自己的看法。
posted on 2009-08-13 14:38 CLive Studio 阅读(987) 评论(0) 编辑 收藏 举报