Tower of Hanoi Recursion Algorithm
10,762
Moving a N disks tower from peg A to C is achieved by moving a N-1 (all disks but the last one) tower from A to B, then moving the Nth disk from A to C, and finally moving the tower previously moved to B, from B to C. This shall be applied any time a tower with more than one disk is moved, in the case of a 1 disk tower, you just move its only disk.
Author by
user564927
Updated on July 24, 2022Comments
-
user564927 almost 2 years
I am having a problem understanding this Tower of Hanoi recursion algorithm:
public class MainClass { public static void main(String[] args) { int nDisks = 3; doTowers(nDisks, 'A', 'B', 'C'); } public static void doTowers(int topN, char from, char inter, char to) { if (topN == 1){ System.out.println("Disk 1 from " + from + " to " + to); }else { doTowers(topN - 1, from, to, inter); System.out.println("Disk " + topN + " from " + from + " to " + to); doTowers(topN - 1, inter, from, to); } } }
The output is:
Disk 1 from A to C Disk 2 from A to B Disk 1 from C to B Disk 3 from A to C Disk 1 from B to A Disk 2 from B to C Disk 1 from A to C
I don't understand how do we get:
Disk 1 from C to B Disk 3 from A to C Disk 1 from B to A
Can someone please explain?
Thank you.
-
user564927 over 11 yearsI understood the whole working.... but when i am trying to recursivly break it down all i get is Disk 1 from A to C Disk 2 from A to B ,Disk 2 from B to C Disk 1 from A to C. I am somehow not able to understand how the recursive function got Disk 1 from C to B Disk 3 from A to C Disk 1 from B to A :(