career cup:3.4 tower of hanoi

本文探讨了使用不同数据结构解决汉诺塔问题的方法,包括使用LinkedList和ArrayList表示塔,并通过BFS算法寻找解决方案。此外,还介绍了递归方法解决该问题的思路。

1. represent of hanoi: choice between LinkedList, Stack, ArrayList, Array

(1) one tower can be represented by LinkedList or Stack. LinkedList has more function and it's easier to copy the tower. We need copy the tower

because we use BFS

(2) Array can not contain things like Stack<Integer>, LinkedList<Integer>, since Stack<Integer>[] = new Stack<Integer>[5] will fail. We can use ArrayList instead.


(3) use LinkedList of int[2] to represent the solution, the solution should be a field of Hanoi state and be copied. Otherwise there exists concurrency problem


2. use BFS:

(1) convert the state of tower to a String as key of HashSet so that we can easily mark the visited state. I use "," to separate the tower in Hanoi

(2) In the loop of BFS, if a certain string(state of Hanoi) is not in the HashSet, do not forget to add it  into the HashSet or the loop will not stop.


3. Another Way: much simper: recursion process
(1) solve 1 disk case: directly move disk from tower1 to tower3
(2) solve 2 disks case: based on case1, move disk1 to tower2, move disk2 to tower3, move disk1 to tower3
(3) solve 3 disks case: based on case 2, move disk1,2 to tower2, move disk 3 to tower3
       based on case 2, move disk 1,2 to tower3
(4) solve 4 disks case: based on case 3, move disk 1,2,3 to tower2, move disk 4 to tower3
       based on case 4, move disk 1,2,3 to tower3
and so on.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值