NOW Hiring

Quick links

Share

Towers of Hanoi in Java. This article describes how to solve the Towers of Hanoi in Java.

1. Towers of Hanoi

The towers of hanoi is a popular problem. You have three poles and n disks which fit on the poles. All disks have different sizes. They are stacked on pole 1 in the order of their sizes. The largest disk is on the bottom, the smallest is on the top.

The task is to move all disk from pole 1 to pole 3 under the following restrictions.

  • Only one disk can be moved.

  • A larger disk can not be placed on a smaller disk.

The recursive algorithm works like the following: move n-1 disk from the starting pole to the pole which is neither start nor target (intermediate), move disk n to the target pole and then move n-1 disk from the intermediate pole to the target pole. The n-1 disks are moved recursively.

2. Implementation in Java

Create a Java project "de.vogella.algorithms.towersofhanoi".

Create the following program.

package de.vogella.algorithms.towersofhanoi;

/**
 * Towers of Hanoi
 * Pole are labeled 1, 2,3
 * Each disk is also labeled
 * @author Lars Vogel
 *
 */
public class TowersOfHanoi {
        public static void move(int n, int startPole, int endPole) {
                if (n== 0){
                        return;
                }
                int intermediatePole = 6 - startPole - endPole;
                move(n-1, startPole, intermediatePole);
                System.out.println("Move " +n + " from " + startPole + " to " +endPole);
                move(n-1, intermediatePole, endPole);
        }

        public static void main(String[] args) {
                move(5, 1, 3);
        }


}

3. About this website

4. Links and Literature

4.1. Source Code

Not listed yet.

4.3. vogella GmbH training and consulting support

TRAINING SERVICE & SUPPORT

The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2016 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.