public class HanNuoTa {
public static void move(int sum, Stack<Integer> left, Stack<Integer> middle, Stack<Integer> right) {
if (sum == 1) {
right.push(left.pop());
return;
} else {
// 把左边的柱子除去最大的罗盘都移到中间的柱子上
move(sum - 1, left, right, middle);
// 把左边的柱子上最底下的那个罗盘移到最右边的柱子上
move(1, left, middle, right);
// 然后把中间柱子上的罗盘全部移到最右边的柱子上
move(sum - 1, middle, left, right);
}
}
public static void main(String[] args) {
// 初始化数据
Stack<Integer> left = new Stack<>();
Stack<Integer> middle = new Stack<>();
Stack<Integer> right = new Stack<>();
left.push(5);
left.push(4);
left.push(3);
left.push(2);
left.push(1);
// 递归
move(left.size(), left, middle, right);
// 打印
while (!right.isEmpty()) {
System.out.println(right.pop());
}
}
}
网友评论