带有堆栈实现和递归的河内塔(Java)

带有堆栈实现和递归的河内塔(Java),java,algorithm,recursion,stack,towers-of-hanoi,Java,Algorithm,Recursion,Stack,Towers Of Hanoi,我试图通过递归来解决河内塔的问题,同时使用堆栈。使用n个大小不断增加的磁盘,输出应如下所示。磁盘必须从柱1移动到柱3,每次移动一个: // assuming n = 3; Pillar1: 3 2 1 Pillar2: Pillar3: // "\n" Pillar1: 3 2 Pillar2: Pillar3: 1 // "\n" Pillar1: 3 Pillar2: 2 Pillar3: 1 // "\n" Pillar1: 3 Pillar2: 2

我试图通过递归来解决河内塔的问题,同时使用堆栈。使用n个大小不断增加的磁盘,输出应如下所示。磁盘必须从柱1移动到柱3,每次移动一个:

// assuming n = 3;

Pillar1: 3 2 1

Pillar2:

Pillar3: 

// "\n"

Pillar1: 3 2 

Pillar2:

Pillar3: 1

// "\n"

Pillar1: 3 

Pillar2: 2

Pillar3: 1


// "\n"

Pillar1: 3 

Pillar2: 2 1

Pillar3: 


// "\n"

Pillar1: 

Pillar2: 2 1

Pillar3: 3


// "\n"

Pillar1: 1

Pillar2: 2

Pillar3: 3

// "\n"

Pillar1: 1

Pillar2: 

Pillar3: 3 2


// "\n"

Pillar1: 

Pillar2: 

Pillar3: 3 2 1
我的代码如下,磁盘>1时,我的输出很难处理:

import java.util.*;
class TowersOfHanoiThree
{
   public static Stack<Integer>[] tower = new Stack[4];
   public static int temp;

   public static void TowersOfHanoiThree(int numDisk)
   {
      //adding disk to stack
      temp = numDisk;
      tower = new Stack[4];

      for(int a = 0; a <= 3; a++)
      {
         tower[a] = new Stack<Integer>();
      }

     for (int i = numDisk; i > 0; i--)
     {
        tower[1].push(numDisk);
        show();
     }
     solver(numDisk, 1, 3, 2);
 }

public static void show()
{
   //System.out.println("Pillar1: ");
   //System.out.println("Pillar2: ");
   //System.out.println("Pillar3: ");

   String Pillar1 = "Pillar1: ";
   String Pillar2 = "Pillar2: ";
   String Pillar3 = "Pillar3: ";

   for(int x = temp -1 ; x >= 0 ; x--)
   {
      String emptStr1 = "";
      String emptStr2 = "";
      String emptStr3 = "";

     try
     {
        emptStr1 = String.valueOf(tower[1].get(x));
     }
     catch(Exception e)
     {
     }

     try
     {
        emptStr2 = String.valueOf(tower[2].get(x));
     }
     catch(Exception e)
     {
     }

     try
     {
        emptStr3 = String.valueOf(tower[3].get(x));
     }
     catch(Exception e)
     {
     }
     System.out.print(Pillar1+emptStr1+"\n");
     System.out.print(Pillar2+emptStr2+"\n");
     System.out.print(Pillar3+emptStr3+"\n");
     System.out.print("\n");
  }
}//end show

public static void solver(int numDisk, int start, int middle, int end) 
{
   if(numDisk > 0) 
   {
      try
      {
         //sorting disks
         solver(numDisk - 1, start, end, middle);
         int dis = tower[start].pop(); //move disk top-most disk of start
         tower[middle].push(dis);
         show();
         solver(numDisk - 1, middle, start, end);
      }
      catch(Exception e)
      {
      }
   }
}

public static void main(String args[])
{
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();

    TowersOfHanoiThree(2);
}
}
import java.util.*;
三等塔楼
{
公共静态堆栈[]塔=新堆栈[4];
公共静态温度;
红宝石树公共静态空塔(国际努姆迪斯克)
{
//将磁盘添加到堆栈
温度=numDisk;
塔=新烟囱[4];
对于(int a=0;a 0;i--)
{
塔[1]。推送(numDisk);
show();
}
解算器(numDisk,1,3,2);
}
公共静态void show()
{
//System.out.println(“Pillar1:”);
//System.out.println(“Pillar2:”);
//System.out.println(“Pillar3:”);
字符串Pillar1=“Pillar1:”;
字符串Pillar2=“Pillar2:”;
字符串Pillar3=“Pillar3:”;
对于(int x=temp-1;x>=0;x--)
{
字符串emptStr1=“”;
字符串emptStr2=“”;
字符串emptStr3=“”;
尝试
{
emptStr1=String.valueOf(塔[1].get(x));
}
捕获(例外e)
{
}
尝试
{
emptStr2=String.valueOf(塔[2].get(x));
}
捕获(例外e)
{
}
尝试
{
emptStr3=String.valueOf(塔[3].get(x));
}
捕获(例外e)
{
}
系统输出打印(Pillar1+emptStr1+“\n”);
系统输出打印(Pillar2+emptStr2+“\n”);
系统输出打印(柱3+emptStr3+“\n”);
系统输出打印(“\n”);
}
}//演出结束
公共静态无效解算器(int numDisk、int start、int middle、int end)
{
如果(numDisk>0)
{
尝试
{
//排序磁盘
解算器(numDisk-1,开始,结束,中间);
int dis=tower[start].pop();//将磁盘移动到start的最顶端
塔架[中间]。推力(dis);
show();
解算器(numDisk-1、中间、开始、结束);
}
捕获(例外e)
{
}
}
}
公共静态void main(字符串参数[])
{
塔[1]=新堆栈();
塔[2]=新堆栈();
塔[3]=新堆栈();
檀香树塔(2);
}
}

使用以下实现应该会为您提供所需的结果。我还添加了一些带有修改的内联注释

public static void TowersOfHanoiThree(int numDisk)
{
  //adding disk to stack
  temp = numDisk;
  tower = new Stack[4];

  for(int a = 0; a <= 3; a++)
  {
     tower[a] = new Stack<Integer>();
  }

 for (int i = numDisk; i > 0; i--)
 {
    tower[1].push(i); // to show "1 2 3" i changed the value which was pushed in the stack
// from tower[1].push(numDisk) to tower[1].push(i)
 }
 show(); //In your example this method call was placed inside the for loop.
//Moving it outside will show the stacks only after the values are added
 solver(numDisk, 1, 3, 2);
}

 public static void show() {
    // System.out.println("Pillar1: ");
    // System.out.println("Pillar2: ");
    // System.out.println("Pillar3: ");

    String Pillar1 = "Pillar1: ";
    String Pillar2 = "Pillar2: ";
    String Pillar3 = "Pillar3: ";

    String emptStr1 = "";
    String emptStr2 = "";
    String emptStr3 = "";
//the empStr variable are moved outside the loop because only after the 
//loop has finished we know what values are in each pillar
    for (int x = 0; x <= temp - 1; x++) {

        try {
//here we just append the values from the pillar to string empStr1
            emptStr1 += String.valueOf(tower[1].get(x)) + " ";
        } catch (Exception e) {
        }

        try {
            emptStr2 += String.valueOf(tower[2].get(x)) + " ";
        } catch (Exception e) {
        }

        try {
            emptStr3 += String.valueOf(tower[3].get(x)) + " ";
        } catch (Exception e) {
        }
    }
//finally when the loop is done we have the results
    System.out.print(Pillar1 + emptStr1 + "\n");
    System.out.print(Pillar2 + emptStr2 + "\n");
    System.out.print(Pillar3 + emptStr3 + "\n");
    System.out.print("\n");
}// end show
hanoithree的公共静态空塔(int numDisk)
{
//将磁盘添加到堆栈
温度=numDisk;
塔=新烟囱[4];
对于(int a=0;a 0;i--)
{
塔[1]。推送(i);//为了显示“1 2 3”,我更改了在堆栈中推送的值
//从塔[1]。推送(numDisk)到塔[1]。推送(i)
}
show();//在您的示例中,此方法调用放置在for循环中。
//将其移到外部将仅在添加值后显示堆栈
解算器(numDisk,1,3,2);
}
公共静态void show(){
//System.out.println(“Pillar1:”);
//System.out.println(“Pillar2:”);
//System.out.println(“Pillar3:”);
字符串Pillar1=“Pillar1:”;
字符串Pillar2=“Pillar2:”;
字符串Pillar3=“Pillar3:”;
字符串emptStr1=“”;
字符串emptStr2=“”;
字符串emptStr3=“”;
//empStr变量被移到循环外,因为只有在
//循环已完成,我们知道每个支柱中的值

对于(intx=0;x,使用下面的实现应该会为您提供所需的结果

public static void TowersOfHanoiThree(int numDisk)
{
  //adding disk to stack
  temp = numDisk;
  tower = new Stack[4];

  for(int a = 0; a <= 3; a++)
  {
     tower[a] = new Stack<Integer>();
  }

 for (int i = numDisk; i > 0; i--)
 {
    tower[1].push(i); // to show "1 2 3" i changed the value which was pushed in the stack
// from tower[1].push(numDisk) to tower[1].push(i)
 }
 show(); //In your example this method call was placed inside the for loop.
//Moving it outside will show the stacks only after the values are added
 solver(numDisk, 1, 3, 2);
}

 public static void show() {
    // System.out.println("Pillar1: ");
    // System.out.println("Pillar2: ");
    // System.out.println("Pillar3: ");

    String Pillar1 = "Pillar1: ";
    String Pillar2 = "Pillar2: ";
    String Pillar3 = "Pillar3: ";

    String emptStr1 = "";
    String emptStr2 = "";
    String emptStr3 = "";
//the empStr variable are moved outside the loop because only after the 
//loop has finished we know what values are in each pillar
    for (int x = 0; x <= temp - 1; x++) {

        try {
//here we just append the values from the pillar to string empStr1
            emptStr1 += String.valueOf(tower[1].get(x)) + " ";
        } catch (Exception e) {
        }

        try {
            emptStr2 += String.valueOf(tower[2].get(x)) + " ";
        } catch (Exception e) {
        }

        try {
            emptStr3 += String.valueOf(tower[3].get(x)) + " ";
        } catch (Exception e) {
        }
    }
//finally when the loop is done we have the results
    System.out.print(Pillar1 + emptStr1 + "\n");
    System.out.print(Pillar2 + emptStr2 + "\n");
    System.out.print(Pillar3 + emptStr3 + "\n");
    System.out.print("\n");
}// end show
hanoithree的公共静态空塔(int numDisk)
{
//将磁盘添加到堆栈
温度=numDisk;
塔=新烟囱[4];
对于(int a=0;a 0;i--)
{
塔[1]。推送(i);//为了显示“1 2 3”,我更改了在堆栈中推送的值
//从塔[1]。推送(numDisk)到塔[1]。推送(i)
}
show();//在您的示例中,此方法调用放置在for循环中。
//将其移到外部将仅在添加值后显示堆栈
解算器(numDisk,1,3,2);
}
公共静态void show(){
//System.out.println(“Pillar1:”);
//System.out.println(“Pillar2:”);
//System.out.println(“Pillar3:”);
字符串Pillar1=“Pillar1:”;
字符串Pillar2=“Pillar2:”;
字符串Pillar3=“Pillar3:”;
字符串emptStr1=“”;
字符串emptStr2=“”;
字符串emptStr3=“”;
//empStr变量被移到循环外,因为只有在
//循环已完成,我们知道每个支柱中的值

对于(int x=0;x,您需要解决一些问题。我将尽力解释它们并提供可能的解决方案

首先,您总是将
numdisk
推到您的
树状结构(int)
方法中的初始堆栈(支柱)上。 冒犯的部分:

for (int i = numDisk; i > 0; i--) {
   tower[1].push(numDisk); // should be tower[1].push(i);
   show();
}
修正:

其次,您的
show()
方法不正确,原因如下:

  • 您应该从索引0而不是最后一个索引(
    temp-1
    )开始迭代阵列
    塔中的每个堆栈,因为您希望从下到上显示磁盘
  • 你应该在
    for
    循环之前声明你的字符串
    emptStr1
    emptStr2
    emptStr3
    。目前你在每次迭代中将它们重置为空字符串
  • 您需要将磁盘连接到字符串
    emptStr1
    emptStr2
    emptStr3
    ,而不是通过重新分配来覆盖它们
  • 您应该在for循环之后输出字符串
    emptStr1
    emptStr2
    emptStr3
  • 我建议完全重写
    show()
    ,例如:

    public static void show() {
        for (int i = 1; i < tower.length; i++) { // iterate over your array of stacks
            String pillar = "Pillar " + i + ":"; // e.g. "Pillar 1: "
            for (int disk : tower[i]) { // iterate over the stack located at index i
                pillar += " " + disk; // concatenate the current disk to the String
            }
            System.out.println(pillar); // Display this pillar
        }
        System.out.println(); // Line break to seperate the show() calls
    }
    
    这应改为:

    solver(numDisk - 1, end, middle, start);
    
    另外,虽然不是失败的原因,但您的阵列
    塔的容量应为4,但应为3。您当前忽略了索引0。我猜想您是有意这样做的,因为您希望将支柱显示为1、2和3?在任何情况下,这都可能是错误的
    
    solver(numDisk - 1, end, middle, start);