Example of a Java solution to a hanotta problem

  • 2020-04-01 03:00:24
  • OfStack

The idea is as follows:

To realize the solution step of the third-order hannotta, that is to say, in the initial state, there are three plates on A from top to bottom, namely plate 1, plate 2 and plate 3, of which plate 1 is the smallest and plate 3 is the largest.
Determine the number of remaining plates. If there is only one plate, exit the iteration. If there is more than one plate, continue the iteration.
The code is as follows:


public class HanoiTower {
    public static void moveDish(int level, char from, char inter, char to) {
        if (level == 1) {//Exit the iteration if there is only one plate
            System.out.println(" from  " + from + "  Mobile plate  1  Number to  " + to);
        } else {//If you have more than one plate, keep iterating
            moveDish(level - 1, from, to, inter);
            System.out.println(" from  " + from + "  Mobile plate  " + level + "  Number to  " + to);
            moveDish(level - 1, inter, from, to);
        }
    }

    public static void main(String[] args) {
        int nDisks = 3;//Set the hanno tower to order 3
        moveDish(nDisks, 'A', 'B', 'C');//Implement the moving algorithm
    }
}


Related articles: