2014-09-25 36 views
0

我試圖實現以下僞代碼:塔非常具體的僞代碼

place all disks in peg 0 
p1 = 0 // Disk 1 is located in peg p1, which is peg 0 
Loop { 
move Disk 1 from peg p1 to peg (p1 + 1) % 3 
p1 = (p1 + 1) % 3 // update peg location of Disk 1 
p = (p1 + 1) % 3 
p' = (p1 + 2) % 3 
// peg p and peg p' are the two other pegs besides peg p1 
if peg p and peg p' are both empty 
then return // we are done with the moves 
else if peg p is empty 
then move the top disk in peg p' to peg p 
else if peg p' is empty 
then move the top disk in peg p to peg p' 
else 
let d = top disk of peg p 
let d' = top disk of peg p' 
if d < d' 
then move disk d from peg p to peg p' 
else move disk d' from peg p' to peg p 
} 

但我遇到了問題。例如,我使用了一個二維數組,但在行中得到了垃圾,我不太確定我將如何跟蹤哪個磁盤位於p和p之上。對不起,但很長的帖子,但在此先感謝這裏是我遇到了牆壁:

public static void moveIt(int n, int p1, int p, int pp) 
    { 
     p1=0; 
     int pegs[][]=new int[3][n]; 
     pegs[p1][0]=n; 
     pegs[p][0]=0; 
     pegs[pp][0]=0; 
     while(true) 
     { 
      System.out.println("move disk 1 from peg "+p1+" to peg "+(p1+1)%3); 
      pegs[p1][0]=pegs[p1][0]-1; 
      pegs[(p1+1)%3][0]=pegs[(p1+1)%3][0]-1; 
      p1=(p1+1)%3; 
      p=(p1+1)%3; 
      pp=(p1+2)%3; 
      System.out.println(pegs[p][0]); 
      if((pegs[p][0]==0)&&(pegs[pp][0]==0)) 
       return; 
      else if(pegs[p][0]==0) 
       System.out.println("move the disk "+n+" in peg "+pp+" to peg "+p); 
      else if(pegs[pp][0]==0) 
       System.out.println("move the top disk in peg "+p+" to peg "+pp); 
     } 
    } 
+0

什麼是n,p1,p和pp?什麼是輸入/輸出組合? – 2014-09-25 02:09:51

+0

n是磁盤的數量,p1開始爲塔0,p開始爲塔1,pp開始爲塔2 – user4077318 2014-09-25 02:12:23

+0

是否允許使用數組列表?還是它必須是一個數組對象? – 2014-09-25 02:18:47

回答

0

謝謝你的幫助。我最終使用堆棧,並基於p = 0,p = 1和p = 2時的整個代碼。它很長,很醜,但它使用給定的僞代碼