0% found this document useful (0 votes)
6 views

Tower of Hanoi recursive solution

Uploaded by

ujjwalanand963
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Tower of Hanoi recursive solution

Uploaded by

ujjwalanand963
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

The Tower of Hanoi is a classic problem in recursion where the goal is to

move a stack of disks from one peg to another, following three rules:

1. Only one disk can be moved at a time.


2. A disk can only be moved to the top of another peg if it is smaller
than the disk already on the peg.
3. Only the top disk from any peg can be moved.

The recursive solution involves breaking down the problem into smaller
sub-problems:

1. Move n−1n - 1n−1 disks from the source peg to an auxiliary peg.
2. Move the largest disk from the source peg to the target peg.
3. Move the n−1n - 1n−1 disks from the auxiliary peg to the target
peg.

Here's the recursive Python function to solve the Tower of Hanoi:

def tower_of_hanoi(n, source, target, auxiliary):

# Base case: If there's only one disk, move it directly from source to
target

if n == 1:

print(f"Move disk 1 from {source} to {target}")

return

# Step 1: Move n-1 disks from source to auxiliary, using target as


auxiliary

tower_of_hanoi(n - 1, source, auxiliary, target)

# Step 2: Move the nth disk from source to target

print(f"Move disk {n} from {source} to {target}")


# Step 3: Move the n-1 disks from auxiliary to target, using source as
auxiliary

tower_of_hanoi(n - 1, auxiliary, target, source)

# Example: Solve Tower of Hanoi for 3 disks

tower_of_hanoi(3, 'A', 'C', 'B')

Explanation:

 n: The number of disks to move.


 source: The peg where the disks initially are.
 target: The peg where the disks need to be moved.
 auxiliary: The peg that is used as a temporary storage while
moving the disks.

You might also like