Skip to content

How to Solve the Tower of Hanoi Problem in Batch Script

Learn how to implement the classic Tower of Hanoi puzzle using recursion in a Windows Batch script, including the recursive algorithm, implementation code, and key considerations like exponential move growth and call stack limits.

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:

  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack.
  3. 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:

  1. Move N−1 disks from the Source rod to the Auxiliary rod.
  2. Move the remaining disk (the largest) from the Source to the Destination rod.
  3. Move the N−1 disks from the Auxiliary to the Destination rod.

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?

  1. Recursion Demonstration: It is the quintessential example of how a function can call itself to solve a complex problem.
  2. Logic Training: Understanding how to break a large task down into smaller, identical sub-tasks is a vital skill for building complex automation.
  3. 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

  1. 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.
  2. 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.
  3. Variable Isolation: Notice the use of setlocal inside the function. This is critical, without it, the n, src, and dst variables would be overwritten by every sub-call, breaking the logic entirely.

Best Practices

  1. Move Counter: Always maintain a global move counter to verify that your solution produces exactly 2^n − 1 moves, confirming algorithmic correctness.
  2. Input Validation: Guard against non-numeric input, zero, negative numbers, and excessively large values to prevent runaway recursion or cryptic error messages.

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.

Navigation