Skip to content

Instantly share code, notes, and snippets.

@RadianSmile
Last active November 2, 2015 17:19
Show Gist options
  • Save RadianSmile/a4466b2c9c81b3c4a36f to your computer and use it in GitHub Desktop.
Save RadianSmile/a4466b2c9c81b3c4a36f to your computer and use it in GitHub Desktop.
Hanoi for Alice
import java.util.*;
/* Class TowerOfHanoiUsingStacks */
public class HanoiStacks {
public static int N;
public static Stack<Integer>[] tower = new Stack[4];
// 為什麼是 4 ? 因為為了要用到 1 , 2 , 3 這個數字,不用 0
public static void main(String[] args) {
// 接收電腦輸入
System.out.println("Enter number of disks");
Scanner scan = new Scanner(System.in);
N = scan.nextInt();
scan.close();
// 準備好 stack 以及 把盤子放到柱子。
init(N);
// 把所有的盤子從原本的柱子 1 移動到柱子柱子 3
HANOI(N, 1, 2, 3);
}
/* Function to push disks into stack */
public static void init(int n) {
// 先把 array 做初始化
tower[1] = new Stack<Integer>();
tower[2] = new Stack<Integer>();
tower[3] = new Stack<Integer>();
// 先在第一個柱子裡放滿所有的數字,越底下數字越大
for (int d = n; d > 0; d--) tower[1].push(d);
display();
}
/* Recursive Function to move disks */
public static void HANOI(int n, int a, int b, int c) {
// 當我移動 0 個盤子的時候
if(n == 1){
//**如果我只有一個盤子,那我就直接把盤子放到C就好啦
int d = tower[a].pop();
tower[c].push(d);
display();
}
else {
//**如果我有一個盤子以上
// 那我就先把 前面 n-1 個盤子移到暫存柱子(B)
HANOI(n-1, a, c, b);
// 然後我就能把最底下的盤子移到目標(C)
HANOI(1, a, b, c);
// 然後再把放在暫存柱子(B)的 n-1 個盤子放到目標柱子(C)來。
HANOI(n-1, b, a, c);
}
}
// 顯示
public static void display() {
System.out.println(" A | B | C");
System.out.println("---------------");
// 把每個柱子的每一層都印出來。
for (int i = N - 1; i >= 0; i--) {
// tower [1].get(0) // 柱子最下層的盤子
// tower [1].get(N-1) // 柱子最上層的盤子
String d1 = " ", d2 = " ", d3 = " ";
// try 柱子的那一層有沒有盤子,如果沒有盤子就進到 catch (也就是不做事情)。
try {
d1 = String.valueOf(tower[1].get(i)); } catch (Exception e) {}
try {
d2 = String.valueOf(tower[2].get(i)); } catch (Exception e) {}
try {
d3 = String.valueOf(tower[3].get(i)); } catch (Exception e) {}
System.out.println(" " + d1 + " | " + d2 + " | " + d3);
}
System.out.println("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment