我正在尝试实现以下psuedo代码:
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);
}
}
感谢您的帮助。我最终使用了堆栈,并基于p=0、p=1和p=2时的整个代码。它很长,也很难看,但它使用给定的伪代码