Han Ruo Tower problem (Basic Han Ruo Tower) - java implementation

Tower of Hanoi problem:

      In ancient times, there was a Buddhist pagoda. There were three seats A, B, and C in the pagoda. There were 64 plates on the A seat, and the plates were different in size. A monk wanted to move the 64 plates from seat A to seat B, but only one plate was allowed to be moved at a time, and during the movement, the plates on the three seats always kept the large plate on the bottom and the small plate on the top. Block B can be used in the moving process, requiring printing of moving steps. If there is only one plate, you don't need to use the B seat and directly move the plate from A to C.

    This problem requires the use of recursive thinking, go directly to the code, I have added a detailed explanation to each sentence in the code, and you can leave a message if you have any questions.

HanoiTower class:

public class HanoiTower {
	//N disks are moved from A through B to C
	//Mark the plate from small to large 1 --> n number
	public static void moveTower(int n,char A,char B,char C) {
		//If there is only 1 plate, move directly from A to C
		if(n == 1) {
			System.out.println("Disk 1 moved from "+A+" to "+C);
		}
		else {
			//Otherwise the above n-1 plates are moved to the B column through C
			moveTower(n - 1, A, C, B);
			//Then move the nth plate directly from A to C column
			System.out.println("disk" + n + "move from " + A + " to " + C);
			// Then move the rest of the plates that are moved to B to C through A, and you're done
			moveTower(n - 1, B, A, C);
			//Through recursion, the incoming n will gradually decrease, the position corresponding to ABC will also change continuously, and finally resolve to move a plate
		}
	}
}

Test class:

public class test {
	public static void main(String[] args) {
		HanoiTower.moveTower(5,'A','B','C');
	}
}

Result of running:

Drive 1 from A to C
Drive 2 from A to B
Drive 1 from C to B
Drive 3 From A to C
Drive 1 from B to A
Drive 2 From B to C Drive
1 From A to C
4 Move from A to B
drive 1 Move from C to B
drive 2 Move from C to A
drive 1 Move from B to A
drive 3 Move from C to B
drive 1 Move from A to C
drive 2 Move from A to B
drive 1 move from C to B
drive 5 move from A to C
drive 1 move from B to A
drive 2 move from B to C
drive 1 move from A to C
drive 3 move from B to A
drive 1 move from C to B
drive 2 from C moved to A
drive 1 moved from B to A
drive 4 moved from B to C
drive 1 moved from A to C
drive 2 moved from A to B
drive 1 moved from C to B
drive 3 moved from A to C
drive 1 moved from B Move to A
drive 2 Move from B to C
drive 1 Move from A to C


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325591653&siteId=291194637