Home / Data structures and Algorithms by Java Examples / Recursion / Tower of Hanoi using Recursion in Java Example
Tower of Hanoi using Recursion in Java Example
3222 views.
TowersOfHanoiPuzzle.java
/*
 *
 * A (source tower), B (auxiliary tower) and C (destination tower).
 *
 * Step for n towers to move towards A to C using B. Can move one at a time. use empty tower as auxiliary tower.
 *
 * Steps:
 * 1) Move n-1 A(source) to B(destination) using C(auxiliary).
 * 2) Move nth from A(source) to C(destination).
 * 3) Move n-1 B(source) to C(destination) using A(auxiliary).

 * If A has 1 rod then move A(source) to C(destination) directly.
 */

class TowersOfHanoiPuzzle {
    public static void TOH(int n,int A, int B, int C) {
        if (n == 1) {
            System.out.println("("+A+","+C+")");
            return;
        }
         
        //Move n-1 A(source) to B(destination) using C(auxiliary).
        TOH(n-1,A,C,B);
         
        //Move nth from A(source) to C(destination).
        System.out.println("("+A+","+C+")");
         
        //Move n-1 B(source) to C(destination) using A(auxiliary).
        TOH(n-1,B,A,C);
    }
     
    public static void main(String[] args) {
        
        //Calling TOH method with 4 rods in three towers (1,2,3).
        TOH(4,1,2,3);
    }
}
Output
(1,2)
(1,3)
(2,3)
(1,2)
(3,1)
(3,2)
(1,2)
(1,3)
(2,3)
(2,1)
(3,1)
(2,3)
(1,2)
(1,3)
(2,3)
Related Examples
   Simple Recursion Example in JAVA
   Print array using recursion JAVA Example
   Recursion on ArrayList Strings in JAVA Example
   Factorial Program using Recursion in JAVA Example
   Fibonacci Series using Recursion in JAVA Example
   Tree Traversal with Recursion in JAVA Example
   Tree Traversal without Recursion Using Stack Class in JAVA Example
   Is ArrayList Ordered using Recursion in JAVA Example
   Tower of Hanoi using Recursion in Java Example
Copyright © 2016 Learn by Examples, All rights reserved