-2

how does each stack in a tower of hanoi problem how is it executed line by line i can't quite understand the way that each stack gets created???

public class TowerOfHanoi {

    public static void towerOfHanoi(int disks, char source, char auxiliary, char destination) {
        if (disks == 0) {
            return;
        }

        towerOfHanoi(disks - 1, source, destination, auxiliary);
        System.out.println(source + " " + destination);
        towerOfHanoi(disks - 1, auxiliary, source, destination);

    }

    public static void main(String[] args) {
        towerOfHanoi(4, 'a', 'b', 'c');
    }
}
George Z.
  • 6,643
  • 4
  • 27
  • 47

1 Answers1

0

This one should work:

private static void hanoiTower(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;
    }
    hanoiTower(n-1, from_rod, aux_rod, to_rod);
    System.out.println("Move disk " + n + " from rod " +  from_rod + " to rod " + to_rod);
    hanoiTower(n-1, aux_rod, to_rod, from_rod);
}
nishantc1527
  • 376
  • 1
  • 12