CSES Solutions - Tower of Hanoi
Last Updated :
28 Mar, 2024
The Tower of Hanoi game consists of three stacks (left, middle, and right) and n round disks of different sizes. Initially, the left stack has all the disks, in increasing order of size from top to bottom. The goal is to move all the disks to the right stack using the middle stack. On each move, you can move the uppermost disk from a stack to another stack. In addition, it is not allowed to place a larger disk on a smaller disk.
The task is to find a solution that minimize the number of moves.
Examples:
Input: n=2
Output: 3
Explanation: Move the topmost(2nd) disk from Stack 1 to Stack 3. Then move the 1st disk from Stack 1 to Stack3 and then, again move the 2nd disk from Stack2 to Stack3.
Input: n=1
Output: 1
Explanation: Move the topmost disk from Stack1 to Stack3.
Approach:
The idea is solve Tower of Hanoi problem using recursion. A recursive approach is employed, breaking down the problem into three main steps: moving 'n-1' disks to an auxiliary stack, transferring the largest disk to the target stack, and finally, moving the 'n-1' disks from the auxiliary stack to the target stack. This recursive strategy ensures an optimal solution with minimal moves for the Tower of Hanoi puzzle.
Follow the steps to solve the problem:
- Initialize three stacks (
sourceStack
, destinationStack
, auxiliaryStack
) representing the left, right, and middle stacks, respectively. - In the recursive moveDisk function,
- If there is only one disk (
diskNumber == 1
), move it directly from the source to the destination and return. - Recursively call
moveDisk
for 'n-1' disks from the source to the auxiliary stack, swapping the roles of destination and auxiliary stacks. - Add the current move to the
moves
vector, indicating the source stack and destination stack. - Recursively call
moveDisk
for 'n-1' disks from the auxiliary to the destination stack, swapping the roles of source and auxiliary stacks.
- Print the total number of moves and Display the sequence of moves, indicating the source stack and destination stack for each move.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Recursive function to move 'diskNumber' disks from
// 'sourceStack' to 'destinationStack' using
// 'auxiliaryStack'
void moveDisk(int diskNumber, vector<vector<int> >& moves,
int sourceStack, int destinationStack,
int auxiliaryStack)
{
// Base case: If there is only one disk, move it
// directly from source to destination
if (diskNumber == 1) {
moves.push_back({ sourceStack, destinationStack });
return;
}
// Recursive call 1: Move 'n-1' disks from source to
// auxiliary, swapping roles of destination and
// auxiliary stacks
moveDisk(diskNumber - 1, moves, sourceStack,
auxiliaryStack, destinationStack);
// Add the current move to the moves vector
moves.push_back({ sourceStack, destinationStack });
// Recursive call 2: Move 'n-1' disks from auxiliary to
// destination, swapping roles of source and auxiliary
// stacks
moveDisk(diskNumber - 1, moves, auxiliaryStack,
destinationStack, sourceStack);
}
// Function to solve Tower of Hanoi problem
void towerOfHanoi(int numberOfDisks)
{
vector<vector<int> >
moves; // Vector to store the sequence of moves
int sourceStack = 1, destinationStack = 3,
auxiliaryStack = 2; // Initialize stack indices
moveDisk(numberOfDisks, moves, sourceStack,
destinationStack,
auxiliaryStack); // Call the recursive function
// Output the total number of moves
cout << moves.size() << "\n";
// Output the sequence of moves (source stack to
// destination stack)
for (auto move : moves) {
cout << move[0] << " " << move[1] << "\n";
}
}
// Driver Code
int main()
{
int numberOfDisks = 2;
towerOfHanoi(
numberOfDisks); // Call the Tower of Hanoi function
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class GFG {
// Function to move 'diskNumber' disks from the 'sourceStack' to 'destinationStack' using 'auxiliaryStack'
public static void moveDisk(int diskNumber, List<int[]> moves, int sourceStack, int destinationStack, int auxiliaryStack) {
// Base case: If there is only one disk and move it directly from source to destination
if (diskNumber == 1) {
moves.add(new int[]{sourceStack, destinationStack});
return;
}
// Recursive call 1: Move 'n-1' disks from the source to auxiliary, swapping roles of destination and auxiliary stacks
moveDisk(diskNumber - 1, moves, sourceStack, auxiliaryStack, destinationStack);
moves.add(new int[]{sourceStack, destinationStack});
moveDisk(diskNumber - 1, moves, auxiliaryStack, destinationStack, sourceStack);
}
// Function to solve Tower of the Hanoi problem
public static void towerOfHanoi(int numberOfDisks) {
List<int[]> moves = new ArrayList<>(); // List to store the sequence of moves
int sourceStack = 1, destinationStack = 3, auxiliaryStack = 2; // Initialize stack indices
moveDisk(numberOfDisks, moves, sourceStack, destinationStack, auxiliaryStack); // Call the recursive function
System.out.println(moves.size());
// Output the sequence of moves.
for (int[] move : moves) {
System.out.println(move[0] + " " + move[1]);
}
}
// Main method
public static void main(String[] args) {
int numberOfDisks = 2;
towerOfHanoi(numberOfDisks);
}
}
Python
# Function to move 'diskNumber' disks from 'sourceStack' to 'destinationStack' using 'auxiliaryStack'
def moveDisk(diskNumber, moves, sourceStack, destinationStack, auxiliaryStack):
# Base case: If there is only one disk, move it directly from source to destination
if diskNumber == 1:
moves.append([sourceStack, destinationStack])
return
# Recursive call 1: Move 'n-1' disks from source to auxiliary, swapping roles of destination and auxiliary stacks
moveDisk(diskNumber - 1, moves, sourceStack, auxiliaryStack, destinationStack)
# Add the current move to the moves list
moves.append([sourceStack, destinationStack])
# Recursive call 2: Move 'n-1' disks from auxiliary to destination, swapping roles of source and auxiliary stacks
moveDisk(diskNumber - 1, moves, auxiliaryStack, destinationStack, sourceStack)
# Function to solve Tower of Hanoi problem
def towerOfHanoi(numberOfDisks):
moves = [] # List to store the sequence of moves
sourceStack, destinationStack, auxiliaryStack = 1, 3, 2 # Initialize stack indices
moveDisk(numberOfDisks, moves, sourceStack, destinationStack, auxiliaryStack) # Call the recursive function
# Output the total number of moves
print(len(moves))
# Output the sequence of moves (source stack to destination stack)
for move in moves:
print(move[0], move[1])
# Driver Code
if __name__ == "__main__":
numberOfDisks = 2
towerOfHanoi(numberOfDisks) # Call the Tower of Hanoi function
JavaScript
// Recursive function to move 'diskNumber' disks from
// 'sourceStack' to 'destinationStack' using
// 'auxiliaryStack'
function moveDisk(diskNumber, moves, sourceStack, destinationStack, auxiliaryStack) {
// Base case: If there is only one disk, move it
// directly from source to destination
if (diskNumber === 1) {
moves.push([sourceStack, destinationStack]);
return;
}
// Recursive call 1: Move 'n-1' disks from source to
// auxiliary, swapping roles of destination and
// auxiliary stacks
moveDisk(diskNumber - 1, moves, sourceStack, auxiliaryStack, destinationStack);
// Add the current move to the moves vector
moves.push([sourceStack, destinationStack]);
// Recursive call 2: Move 'n-1' disks from auxiliary to
// destination, swapping roles of source and auxiliary
// stacks
moveDisk(diskNumber - 1, moves, auxiliaryStack, destinationStack, sourceStack);
}
// Function to solve Tower of Hanoi problem
function towerOfHanoi(numberOfDisks) {
let moves = []; // Array to store the sequence of moves
let sourceStack = 1, destinationStack = 3, auxiliaryStack = 2; // Initialize stack indices
// Call the recursive function
moveDisk(numberOfDisks, moves, sourceStack, destinationStack, auxiliaryStack);
// Output the total number of moves
console.log(moves.length);
// Output the sequence of moves (source stack to
// destination stack)
for (let move of moves) {
console.log(move[0] + " " + move[1]);
}
}
// Driver Code
let numberOfDisks = 2;
towerOfHanoi(numberOfDisks); // Call the Tower of Hanoi function
Time Complexity: O(2n), where n is number of disks.
Auxilary Space: O(n)
Similar Reads
CSES Solutions - Towers You are given n cubes as an array cubes[] in a certain order and contains only distinct elements. Your task is to build towers using them. Whenever two cubes are one on top of the other, the upper cube must be smaller than the lower cube. You must process the cubes in the given order. You can always
6 min read
CSES Solutions - Ferris Wheel There are N children who want to go to a Ferris wheel in the form of array arr[], and your task is to find a gondola for each child. Each gondola may have one or two children in it, and in addition, the total weight in a gondola may not exceed X. You know the weight of every child. What is the minim
6 min read
Implement Tower of Hanoi in C++ Tower of Hanoi is mathematical puzzle in which we have 3 rods and n disks. First, all the disks are arranged in first rod from larger disk to smaller disk. We have to move all the disk from the first disk to last disk in same arrangement from larger to smaller. Rules of Tower of HanoiThere are follo
3 min read
CSES Problem Set Solutions In this article, we have compiled comprehensive, high-quality tutorials on the CSES Problem Set Solutions to assist you in understanding the problem set for learning algorithmic programming. What is CSES Problem Set?CSES Problem Set is a collection of competitive programming tasks hosted on the CSES
8 min read
Recursive Tower of Hanoi using 4 pegs / rods Tower of Hanoi is a mathematical puzzle. Traditionally, It consists of three poles and a number of disks of different sizes which can slide onto any poles. The puzzle starts with the disk in a neat stack in ascending order of size in one pole, the smallest at the top thus making a conical shape. The
8 min read
CSES Solutions - Josephus Problem II Consider a game where there are N children (numbered 1,2 ... N) in a circle. During the game, repeatedly K children are skipped and one child is removed from the circle. In which order will the children be removed? Examples: Input: N = 7, K = 2Output: 3 6 2 7 5 1 4Explanation: children = [1, 2, 3, 4
11 min read