Skip to content

Commit 618f6e1

Browse files
Added new file in divide and conquer folder
1 parent c79034c commit 618f6e1

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
Towers of Hanoi is a mathematical puzzle that is solved using a recursive
3+
divide-and-conquer strategy.
4+
5+
It moves a stack of disks from a source pole to a destination pole,
6+
using an auxiliary pole, subject to these rules:
7+
1. Only one disk can be moved at a time.
8+
2. Each move consists of taking the upper disk from one stack and
9+
placing it on top of another stack or an empty pole.
10+
3. No disk may be placed on top of a smaller disk.
11+
12+
More information:
13+
https://en.wikipedia.org/wiki/Tower_of_Hanoi
14+
"""
15+
16+
17+
def tower_of_hanoi(n: int, source: str = "A", auxiliary: str = "B", destination: str = "C") -> list[tuple[str, str]]:
18+
"""
19+
Pure python implementation of the Towers of Hanoi puzzle (recursive version),
20+
returning the sequence of moves required to solve the puzzle.
21+
22+
>>> tower_of_hanoi(1)
23+
[('A', 'C')]
24+
>>> tower_of_hanoi(2)
25+
[('A', 'B'), ('A', 'C'), ('B', 'C')]
26+
>>> tower_of_hanoi(3)
27+
[('A', 'C'), ('A', 'B'), ('C', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('A', 'C')]
28+
>>> tower_of_hanoi(0)
29+
[]
30+
"""
31+
moves = []
32+
33+
def solve_hanoi(n: int, source: str, auxiliary: str, destination: str):
34+
"""Recursive helper function to generate the moves."""
35+
if n == 0:
36+
return
37+
38+
# 1. Move n-1 disks from Source to Auxiliary, using Destination as auxiliary.
39+
# This is the "Divide" step.
40+
solve_hanoi(n - 1, source, destination, auxiliary)
41+
42+
# 2. Move the largest disk (n) from Source to Destination.
43+
# This is the "Conquer" step (base step of the recursion).
44+
moves.append((source, destination))
45+
46+
# 3. Move n-1 disks from Auxiliary to Destination, using Source as auxiliary.
47+
# This is the "Combine" step.
48+
solve_hanoi(n - 1, auxiliary, source, destination)
49+
50+
solve_hanoi(n, source, auxiliary, destination)
51+
return moves
52+
53+
54+
if __name__ == "__main__":
55+
try:
56+
n_disks = int(input("Enter the number of disks for the Tower of Hanoi: ").strip())
57+
if n_disks < 0:
58+
print("Please enter a non-negative number of disks.")
59+
else:
60+
all_moves = tower_of_hanoi(n_disks)
61+
print(f"\nTotal moves required: {len(all_moves)}")
62+
print("Sequence of Moves (Source -> Destination):")
63+
for move in all_moves:
64+
print(f"Move disk from {move[0]} to {move[1]}")
65+
except ValueError:
66+
print("Invalid input. Please enter an integer.")

0 commit comments

Comments
 (0)