public class HanoiTower {
private static final Stack<Integer> source = new Stack<>(){
@Override
public synchronized int hashCode() {
return 101;
}
};
private static final Stack<Integer> buffer = new Stack<>(){
@Override
public synchronized int hashCode() {
return 102;
}
};
private static final Stack<Integer> target = new Stack<>(){
@Override
public synchronized int hashCode() {
return 103;
}
};
private static int totalCount = 0;
/**
* 移动思路: 将圆盘分为底层圆盘和上册 n-1 个圆盘两个部分递归移动
*/
public static void move(int count, Stack<Integer> source, Stack<Integer> buffer, Stack<Integer> target){
if (count == 1) {
indeedMove(source, target);
return;
}
// 将上层 n - 1 个圆盘以 target 为 buffer 进行移动
move(count - 1, source, target, buffer);
// 将底层从 source 移动到 target
move(1, source, buffer, target);
// 将缓存栈的 n-1 个圆盘移动到 target
move(count - 1, buffer, source, target);
}
/**
* 栈内的数据移动
* @param source 源站
* @param target 目标栈
*/
public static void indeedMove(Stack<Integer> source, Stack<Integer> target){
final Integer pop = source.pop();
target.push(pop);
totalCount++;
System.out.println("数据 [" + pop + "] 从栈 [" + source.hashCode() + "] 移动到栈 [" + target.hashCode() + "]");
}
private static void printStack(Stack<Integer> stack){
System.out.println("栈[" + stack.hashCode() + "] :: " + stack.toString());
}
public static void printAllStack(){
printStack(source);
printStack(buffer);
printStack(target);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入初始的数据个数: ");
int count = scanner.nextInt();
for (int i = count; i > 0; i--) {
source.push(i);
}
printAllStack();
move(count, source, buffer, target);
System.out.println("总共执行了 " + totalCount + " 次移动");
printAllStack();
}
}
使用三个整数栈模拟汉诺塔移动问题
测试
请输入初始的数据个数: 6
栈[101] :: [6, 5, 4, 3, 2, 1]
栈[102] :: []
栈[103] :: []
数据 [1] 从栈 [101] 移动到栈 [102]
数据 [2] 从栈 [101] 移动到栈 [103]
数据 [1] 从栈 [102] 移动到栈 [103]
......
总共执行了 63 次移动
栈[101] :: []
栈[102] :: []
栈[103] :: [6, 5, 4, 3, 2, 1]