YouTip LogoYouTip

Method Tower

# Java Example - Tower of Hanoi Algorithm [![Image 3: Java Example](#) Java Example](#) The Tower of Hanoi (also known as the Tower of Brahma) is a puzzle originating from an ancient Indian legend. When Brahma created the world, he made three diamond pillars. On one pillar, from bottom to top, were stacked 64 golden disks in order of size. Brahma commanded the Brahmins to move the disks from the first pillar to another, following these rules: a smaller disk cannot be placed on top of a larger disk, and only one disk can be moved at a time between the three pillars. Later, this legend evolved into the Tower of Hanoi game, with the following rules: * 1. There are three rods A, B, and C. Rod A has several disks. * 2. Move one disk at a time; a smaller disk can only be placed on top of a larger one. * 3. Move all disks from rod A to rod C. The following example demonstrates the implementation of the Tower of Hanoi algorithm: ## MainClass.java File 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 of the above code 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 [![Image 4: Java Example](#) Java Example](#)
← Python Heap SortPython Bubble Sort β†’