Java program for Tower of Hanoi

 class TowerOfHanoi {

    // Time Complexity O(n) and Space Complexity O(1)

    void tower_recursive(int numberOfDisks, int sourceTower, int additionalTower, int destinationTower) {

        if(numberOfDisks > 0){

            tower_recursive(numberOfDisks - 1, sourceTower, destinationTower, additionalTower);

            System.out.println("Moving disk from tower " + sourceTower + " to " + destinationTower);

            tower_recursive(numberOfDisks - 1, additionalTower, sourceTower, destinationTower);

        }

    }

public static void main (String[] args) {

    TowerOfHanoi obj = new TowerOfHanoi();

    obj.tower_recursive(3, 1, 2, 3);

}

}

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance