public class TowerOfHanoi { public static void solve(int n, char source, char target, char auxiliary) { if (n == 1) { System.out.println("Move disk 1 from " + source + " to " + target); return; } solve(n - 1, source, auxiliary, target); System.out.println("Move disk " + n + " from " + source + " to " + target); solve(n - 1, auxiliary, target, source); } public static void main(String[] args) { int n = 3; // Number of disks solve(n, 'A', 'C', 'B'); // A, B and C are the names of the rods } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter