Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Java Recursion to realize Hanoi Tower Game

Shulou Source: shulou.com Published: 2022-06-02 10:40:34 10月02日 Update

Today, I will talk to you about how to use Java recursion to realize the game of Tower of Hanoi. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

It is easy to imagine that the game of Tower of Hanoi can be realized by recursion. Because we want to move n (n > 1) plates from the "source" column to the "target" column, we need to first move a plate from the "source" column to the "auxiliary" column, then move the bottom plate to the target post, and finally move the nmur1 plate on the "auxiliary column" to the target post. When moving directly to the target column, it is also the exit of recursion.

With the groundwork for the above ideas, you can begin to implement the code.

Public class HanoiDemo {public static int hanoiCalledCount = 0 int / member variable record number of operations / Hanotta game is a two-way recursive public static void main (String [] args) {hanoi (3, "A", "B", "C"); System.out.println ("execute" + hanoiCalledCount+ "step");} public static void hanoi (int njingString source,String target,String assist) {if (n)

Tags: Columns plates targets recursion Hanno move assist content times counters plus one exit number code variables suggestions ideas members numbers time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Redmi vpn MariaDB Docker