Title: Recursion Towers of Hanoi
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Recursion: Towers of Hanoi

Solution for 3 Disks

Solution for 4 Disks

Hanoi.java


import java.util.Scanner;

public class Hanoi {

    void hanoi(int N, char startingPost, char tempPost, char endingPost)
    {
        if (N == 1)
            // Stopping condition for recursion
            System.out.println("Move "+ startingPost + " to " + endingPost + " post");
        else
        {
            // move takes n-1 disks from startPost to
            // tempPost using endPost for temporary storage
            hanoi(N-1, startingPost, endingPost, tempPost);

            // move largest disk to endingPost
            System.out.println("Move " + startingPost + " to " + endingPost + " post");

            // move takes n-1 disks from tempPost to
            // endPost using startPost for temporary storage
            hanoi(N-1, tempPost, startingPost, endingPost);
        }
    }
    public static void main(String[] args) {

        System.out.println("Enter in the number of disks for the Tower of Hanoi: ");
        Scanner keyboard = new Scanner(System.in);
        int N = keyboard.nextInt();

        Hanoi h = new Hanoi();
        h.hanoi(N, 'A', 'B', 'C');


    }

}



Last Updated: July 22, 2014 10:12 PM