Discuss Towers of Hanoi Puzzle.
💻 coding

Discuss Towers of Hanoi Puzzle.

2 min read 307 words
2 min read
ShareWhatsAppPost on X
  • 1The Tower of Hanoi is a mathematical puzzle involving three rods and disks of different sizes arranged in a conical shape.
  • 2The objective is to move the entire stack of disks to another rod, following specific rules about disk movement.
  • 3The solution involves a recursive algorithm that breaks the problem into smaller subproblems, allowing for any number of disks.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The Tower of Hanoi is a mathematical puzzle involving three rods and disks of different sizes arranged in a conical shape."

Discuss Towers of Hanoi Puzzle.

The Tower of Hanoi is a mathematical puzzle. It consists of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks on one rod in ascending order of size the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, satisfying the following rules:

- Only one disk may be moved at a time.

- Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.

- No disk may be placed on top of a smaller disk.

Algorithm

- move the top n-1 disks from Source to Auxiliary tower,

- Move the nth disk from Source to Destination tower,

- Move the (n-1)th disks from Auxiliary tower to Destination tower.

- Transferring the top (n-1) disks from Source to Auxiliary tower can again be thought of as a fresh problem and can be solved in the same manner. Once we solve Tower of Hanoi with three disks, we can solve it with any number of disks with the above algorithm.

void TowersOfHanoi(int n, char frompeg, char topeg, char auxpeg){
 	// If only 1 disk then move and return
 	if(n == 1) {
 		System.out.println("Move disk 1 from peg "+ frompeg+" to peg "+ topeg);
 		return;
 	}
 	// Move top (n-1) disks from A to B, using C as Auxiliary
 	TowersOfHanoi(n-1, frompeg, auxpeg, topeg);
 	
 	//Move remaining disks from A to C
 	System.out.println("Move disk from peg "+frompeg+" to peg "+ topeg);
 	
 	// Move (n-1) disks from B to C using A as Auxiliary
 	TowersOfHanoi(n-1, auxpeg, topeg, frompeg);
 }

source: Data Structures and Algorithms Made Easy in Java ( By Narasimha Karumanchi )

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 6 August 2018 · 2 min read · 307 words

Part of AskGif Blog · coding

You might also like

Discuss Towers of Hanoi Puzzle. | AskGif Blog