2009年6月15日 星期一

Lab Hanoi Tower

The pseudocode for Hanoi Tower is as follows:

solve(N, Src, Aux, Dst)
if N is 0 return
solve(N-1, Src, Dst, Aux)
Move N from Src to Dst
solve(N-1, Aux, Src, Dst)


Write the Java program based on the pseudocode in the above.


------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class LabHanoiTower {
public static void move(int n, int s, int e)
{
System.out.println("move "+ n + " : " + s + " -> " + e);
}
public static void exchange(int n, int s, int m, int e)
{
Hanoi(n-1, s, e, m);
move(n, s, e);
Hanoi(n-1, m, s, e);
}
public static void Hanoi(int n, int s, int m, int e)
{
if(n==1)
move(n, s, e);
else
exchange(n, s, m, e);
}
    public static void main (String args[]) {
        int n;
n = 4;
Hanoi(n, 1, 2, 3);
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言