How to Solve the Tower of Hanoi Problem in Batch Script
The Tower of Hanoi is a classic mathematical puzzle consisting of three rods and a number of disks of different sizes. The objective is to move the entire stack of disks from the starting rod to the ending rod, following three rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack.
- No disk may be placed on top of a smaller disk.
In this guide, we will demonstrate how to solve this problem using Recursion in a Batch script.
The Strategy: Recursive Functionsā
To solve for N disks:
- Move Nā1 disks from the Source rod to the Auxiliary rod.
- Move the remaining disk (the largest) from the Source to the Destination rod.
- Move the Nā1 disks from the Auxiliary to the Destination rod.
The minimum number of moves required to solve the Tower of Hanoi is 2^n ā 1. For 3 disks this is 7 moves, for 5 disks it is 31, and for 10 disks it is 1,023. The growth is exponential.
Implementation Scriptā
@echo off
setlocal enabledelayedexpansion
:: 1. Initial settings
set /p "disks=Enter number of disks (1-10): "
set "moves=0"
:: Validate input
if !disks! LSS 1 (
echo [ERROR] Number of disks must be at least 1.
pause
exit /b 1
)
if !disks! GTR 10 (
echo [WARNING] Values above 10 will produce over 1,000 moves and may be very slow.
set /p "confirm=Continue? (Y/N): "
if /i not "!confirm!"=="Y" exit /b 0
)
echo.
echo --- Solution for !disks! disks ---
echo Moving from Rod A to Rod C using Rod B as auxiliary.
echo.
:: 2. Start the Recursive Call
:: Usage: call :hanoi [count] [source] [target] [aux]
call :hanoi !disks! A C B
echo.
echo [DONE] Puzzle solved in !moves! moves.
endlocal
pause
exit /b 0
:: ============================================
:: RECURSIVE FUNCTION
:: ============================================
:hanoi
:: Parameters: %1=count %2=source %3=destination %4=auxiliary
setlocal
set "n=%~1"
set "src=%~2"
set "dst=%~3"
set "aux=%~4"
:: Base case: If 1 disk, move it directly
if %n% EQU 1 (
set /a "moves+=1"
echo Move #!moves!: Disk 1 from %src% to %dst%
goto :end_hanoi
)
:: Step 1: Move n-1 disks from source to auxiliary
set /a "nm1=n - 1"
call :hanoi %nm1% %src% %aux% %dst%
:: Step 2: Move the nth (largest remaining) disk
set /a "moves+=1"
echo Move #!moves!: Disk %n% from %src% to %dst%
:: Step 3: Move n-1 disks from auxiliary to destination
call :hanoi %nm1% %aux% %dst% %src%
:end_hanoi
endlocal & set "moves=%moves%"
exit /b
Why Solve the Tower of Hanoi in Batch?ā
- Recursion Demonstration: It is the quintessential example of how a function can call itself to solve a complex problem.
- Logic Training: Understanding how to break a large task down into smaller, identical sub-tasks is a vital skill for building complex automation.
- Algorithmic Benchmarking: Observing how the number of moves grows exponentially (2^n ā 1) allows you to test the limits of your system's stack and variable memory.
Important Considerationsā
Every recursive call in Batch consumes memory on the call stack. With each additional disk, the recursion depth doubles. Testing with more than 15ā20 disks will likely crash CMD with a "Stack overflow" or "Out of memory" error, and even 10 disks produces over 1,000 echoed lines of output.
- Exponential Growth: 3 disks take 7 moves. 10 disks take 1,023 moves. 20 disks take over 1 million moves. Do not test this script with more than 10 disks unless you want to wait a very long time.
- Call Stack Depth: Every recursive call in Batch uses memory. If you have too many disks, Batch will eventually crash with a "Stack overflow" or "Out of memory" error.
- Variable Isolation: Notice the use of
setlocalinside the function. This is critical, without it, then,src, anddstvariables would be overwritten by every sub-call, breaking the logic entirely.
Best Practicesā
- Move Counter: Always maintain a global move counter to verify that your solution produces exactly 2^n ā 1 moves, confirming algorithmic correctness.
- Input Validation: Guard against non-numeric input, zero, negative numbers, and excessively large values to prevent runaway recursion or cryptic error messages.
To redirect the output to a file for later analysis (especially useful for larger disk counts), run the script with: tower_of_hanoi.bat > solution.txt. The move sequence will be written to the file while prompts still appear on screen.
Conclusionā
Solving the Tower of Hanoi in Batch is a masterclass in recursive logic. By breaking a seemingly complex puzzle into a series of three simple recursive steps, you build a script that can manage deep, nested operations with absolute precision. This architectural approach is the foundation for building advanced directory-processing scripts, tree-traversal tools, and any automation that requires "Diving deep" into nested data structures.