This is the 24th day of my participation in the August More Text Challenge

Problem Description:

There are three adjacent pillars, labeled A,B and C. N disks of different sizes are stacked in A pyramid form from bottom to top on pillar A. All the plates should be moved to pillar C one by one, and no large plate can appear on the same pillar above the small plate each time.

Analysis:

Think of it as simple as possible: 1. If n is equal to 1, move it directly to C.

2. If n>2, pillar B is needed for assistance

A :(how to do this while ensuring that the upper disk is not larger than the lower disk) we first move the disks from 1 to n-1 from disk A to pillar B and then n to pillar C, where we need A pillar C as an auxiliary,B. We now think of 3 as being fused with pillar C and the problem becomes to move the disk on pillar B onto C so that the disk on top can’t be bigger than the disk on the bottom

How to do that is the same step as step A and the idea is the same why do you say that because the auxiliary column is going to be different the second time we first move the 1-N-1 disk onto pillar B with C as the auxiliary so now the question is where do we move the 1-N-1 disk on pillar B? Eventually, of course, it will move to drive C. Who should that be? Is it possible to use C as an auxiliary? The answer is no. So the way to think about it is that our goal is to move the rest of the 1-n-1 onto our drive C so we need A to be our auxiliary drive L and then we can do something like AB so that’s the general idea

public class Hanoi { static int count = 0; Public static void Hanoi (int n, char a, char b, char c) {// if (n == 1) { move(a, n, c); // return; } else {// Hanoi (n-1, a, C, b); // step A move(A, n, c); -- Hanoi (n-1, b, A, c) -- Hanoi (n-1, b, A, C) Private static void move(char a, int n, char c) {system.out.println (" char a, int n, char c); (" + n + a + c "); } public static void main(String[] args) { char a = 'A'; char b = 'B'; char c = 'C'; hanoi(5, a, b, c); System.out.println(count); }}Copy the code

Running results:

A — >C; A — >B; C — >B; A — >C; 1 B — >A; B — >C; A — >C; A — >B; C — >B; C — >A; 1 B — >A; C — >B; A — >C; A — >B; C — >B; A — >C; 1 B — >A; B — >C; A — >C; B — >A; C — >B; C — >A; 1 B — >A; B — >C; A — >C; A — >B; C — >B; A — >C; 1 B — >A; B — >C; A — >C;

31