河内塔(递归)

时间:2015-04-12 22:51:23

标签: java recursion

我正在阅读Java编程简介第9版,我对递归函数和计数器有疑问。如何在此程序中添加计数器?即如何在打印出必须制作的电影时打印出程序打印出的内容?

示例输出

将1个磁盘1转为C

将2个磁盘2转为B

程序:

public class Test {

    public static void main(String[] args) {

        int n = 3; // Number of disks

        System.out.println("Tower of hanoi with " + n + " disks");

        TowerHanoi(n, "A", "B", "C"); // Space A is the initial position, B is the storage position, and C is the final destination

    }

    public static void TowerHanoi(int numDisk,String towerStart, String towerStor, String towerDest) {

        if (numDisk == 1) { // Moves disk 1             
            System.out.println("Disk " + numDisk + " to " + towerDest);                 
        }

        else if (numDisk != 1) {

            TowerHanoi(numDisk - 1, towerStart, towerDest, towerStor); // Moves a disk from the starting tower to the destination tower

            System.out.println("Disk " + numDisk + " to " + towerDest);

            TowerHanoi(numDisk - 1, towerStor, towerStart, towerDest); // Recursive call, moves disk from storage to destination                
        }

    }

}

1 个答案:

答案 0 :(得分:0)

我认为最简单(但有点hacky)的解决方案是向Test类添加静态变量,比如

public static int turn = 0;

并在两次“println”调用之前将其打印在TowerHanoi函数中

System.out.print("Turn " + turn++ + " ");
相关问题