Tower of Hanoi

PHOTO EMBED

Sun Feb 06 2022 21:54:48 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #recursion #towerofhanoi #toh

import java.util.*;
import java.io.*;

class GFG 
{ 
    static void ToH(int n, char A, char B, char C) 
    { 
        if (n == 1) 
        { 
            System.out.println("Move 1 from " +  A + " to " + C); 
            return; 
        } 
        ToH(n-1, A, C, B); 
        System.out.println("Move " + n + " from " +  A + " to " + C); 
        ToH(n-1, B, A, C); 
    } 
   
    public static void main(String args[]) 
    { 
        int n = 2; 
        ToH(n, 'A', 'B', 'C');  
    } 
}
content_copyCOPY

Tower of Hanoi is a mathematical puzzle : 3 rods & n disks. Rules: Only one disc moves at a time. No larger disc above smaller. Only the top Disc of a tower can be moved. Examples: Input : 1 Output : Move Disc 1 from A to C Input : 2 Output : Move Disc 1 from A to B Move Disc 2 from A to C Move Disc 1 from B to C Input : 3 Output : Disk 1 moved from A to C Disk 2 moved from A to B Disk 1 moved from C to B Disk 3 moved from A to C Disk 1 moved from B to A Disk 2 moved from B to C Disk 1 moved from A to C { Number of movements for a given 'n' disks = 2^n - 1 }

https://practice.geeksforgeeks.org/problems/tower-of-hanoi-1587115621/1/?track=DSASP-Recursion&batchId=190