📜  河内塔的Java程序

📅  最后修改于: 2022-05-13 01:58:09.282000             🧑  作者: Mango

河内塔的Java程序

河内塔是一个数学难题,我们有三个杆和 n 个圆盘。谜题的目标是将整个堆栈移动到另一根杆上,遵循以下简单规则:
1) 一次只能移动一个磁盘。
2) 每次移动都包括从其中一个堆栈中取出上面的磁盘并将其放在另一个堆栈的顶部,即只有当磁盘是堆栈中最上面的磁盘时才能移动磁盘。
3) 任何磁盘都不能放在较小的磁盘上。
常见问题解答.disk3

Java
// Java recursive program to solve tower of hanoi puzzle
  
class GFG
{
    // Java recursive function to solve tower of hanoi puzzle
    static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
    {
        if (n == 1)
        {
            System.out.println("Move disk 1 from rod " +  from_rod + " to rod " + to_rod);
            return;
        }
        towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
        System.out.println("Move disk " + n + " from rod " +  from_rod + " to rod " + to_rod);
        towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
    }
      
    //  Driver method
    public static void main(String args[])
    {
        int n = 4; // Number of disks
        towerOfHanoi(n, \'A\', \'C\', \'B\');  // A, B and C are names of rods
    }
}
Output:Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 3 from rod A to rod B
 Move disk 1 from rod C to rod A
 Move disk 2 from rod C to rod B
 Move disk 1 from rod A to rod B
 Move disk 4 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 2 from rod B to rod A
 Move disk 1 from rod C to rod A
 Move disk 3 from rod B to rod C
 Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C
Please refer complete article on Program for Tower of Hanoi for more details!