. CareerCup com 118
3.4 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 (e.g., each disk sits on top of an even larger one). 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.
非递归版本以后补充
3.4 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 (e.g., each disk sits on top of an even larger one). 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.
public class Solution{
//recursive
//move layer disks from A to C by B
public static void hanoi(char A, char B, char C, int layer){
if(layer > 0){
if(layer == 1){
System.out.println("<" + (layer - 1) + "> " + A + "->" + C);
}else{
hanoi(A, C, B, layer-1);
System.out.println("<" + (layer - 1) + "> " + A + "->" + C);
hanoi(B, A, C, layer-1);
}
}else{
System.out.println("invalid layer !");
}
}
public static void main(String[] args){
Solution.hanoi('A', 'B', 'C', 3);
}
}
非递归版本以后补充