career cup:3.4 tower of hanoi

来源:互联网 发布:mac程序图标怎么删除 编辑:程序博客网 时间:2024/06/06 14:08

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.

0 0
原创粉丝点击