DSAverse
Initializing Sorting Algorithms...
Sorting Algorithm
Binary Tree
Graph Traversal
Preparing interactive visualizations for optimal learning experience...
Initializing Sorting Algorithms...
Preparing interactive visualizations for optimal learning experience...
Initializing Sorting Algorithms...
Preparing interactive visualizations for optimal learning experience...
Watch the classic divide & conquer algorithm solve the ancient Tower of Hanoi puzzle with elegant recursive moves.
Click Start to begin solving the Tower of Hanoi puzzle
def tower_of_hanoi(n, source, destination, auxiliary):
if n == 1:
# Base case: move single disk
print(f"Move disk 1 from {source} to {destination}")
return
# Step 1: Move n-1 disks from source to auxiliary
tower_of_hanoi(n-1, source, auxiliary, destination)
# Step 2: Move the largest disk from source to destination
print(f"Move disk {n} from {source} to {destination}")
# Step 3: Move n-1 disks from auxiliary to destination
tower_of_hanoi(n-1, auxiliary, destination, source)
# Solve 3-disk Tower of Hanoi
tower_of_hanoi(3, 'A', 'C', 'B')
# Total moves: 7function towerOfHanoi(n, source, destination, auxiliary) {
if (n === 1) {
console.log(`Move disk 1 from ${source} to ${destination}`);
return;
}
// Move n-1 disks to auxiliary
towerOfHanoi(n-1, source, auxiliary, destination);
// Move largest disk to destination
console.log(`Move disk ${n} from ${source} to ${destination}`);
// Move n-1 disks to destination
towerOfHanoi(n-1, auxiliary, destination, source);
}
// Solve 3-disk puzzle
towerOfHanoi(3, 'A', 'C', 'B'); // 7 moves