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 - Two Knights
Given a number N, the task is to count for each K = 1,2 ⦠N the number of ways two knights can be placed on a K X K chessboard so that they do not attack each other. Examples: Input: N = 2Output: 0 6Explanation: For a 1 X 1 chessboard, there is no possible way to place 2 knights on a 1 X 1 chessboar
7 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
CSES Solutions â Labyrinth
You are given a map of a labyrinth, and your task is to find a path from start to end. You can walk left, right, up and down. The first input line has two integers n and m: the height and width of the map. Then there are lines of m characters describing the labyrinth. Each character is . (floor), #
11 min read
CSES Solutions - Number Spiral
A number spiral is an infinite grid whose upper-left square has the number 1. The task is to find the number in row Y and column X. Here are the first five layers of the spiral: Examples: Input:Â Y = 2, X = 3Output:Â 8Explanation: The 2nd row, 3rd column contains 8. Input:Â Y = 4, X = 2Output:Â 15Explan
9 min read
CSES Solutions - Grid Paths
There are 88418 paths in a 7x7 grid from the upper-left square to the lower-left square. Each path corresponds to a 48-character description consisting of characters D (down), U (up), L (left) and R (right). You are given a description of a path which may also contain characters ? (any direction). Y
15 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 Solutions - Weird Algorithm
Consider an algorithm that takes as input a positive integer N. If N is even, the algorithm divides it by two, and if N is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until N is one. Your task is to simulate the execution of the algorithm for a given value of
4 min read
CSES Solutions â Cycle Finding
Given a directed graph with N nodes and M edges determine if there exists a negative cycle in the graph. If a negative cycle exists print "YES" and output any vertex sequence that forms the cycle; otherwise print "NO". Examples: Input: 4 5 1 2 1 2 4 1 3 1 1 4 1 -3 4 3 -2 Output: YES 1 2 4 1 Approach
11 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