Towers of Hanoi
Solves the classic tower puzzle step by step.
- Level
- Advanced
- Topic:
- Subprocesses & functions
- Concepts:
- Input & output
- SubProcesos
- Recursion
- Si
Run, change and debug this example in your browser.
What you'll learn
Hanoi is a recursive SubProceso: it calls itself with one disk fewer. The base case (a single disk) is what stops the recursion.
Code
SubProceso Hanoi(discos, origen, destino, auxiliar) Si discos = 1 Entonces Escribir "Mover disco 1 de ", origen, " a ", destino SiNo // Primero apartamos los discos de arriba, luego volvemos a apilarlos Hanoi(discos - 1, origen, auxiliar, destino) Escribir "Mover disco ", discos, " de ", origen, " a ", destino Hanoi(discos - 1, auxiliar, destino, origen) FinSiFinSubProcesoAlgoritmo TorresDeHanoi Definir n Como Entero Escribir "¿Cuántos discos? (1 a 6)" Leer n Hanoi(n, "A", "C", "B") Escribir "Total de movimientos: ", 2 ^ n - 1FinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
¿Cuántos discos? (1 a 6)User answer: 3Mover disco 1 de A a CMover disco 2 de A a BMover disco 1 de C a BMover disco 3 de A a CMover disco 1 de B a AMover disco 2 de B a CMover disco 1 de A a CTotal de movimientos: 7
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(2ⁿ) |
| Average | O(2ⁿ) |
| Worst | O(2ⁿ) |
| Memory | O(n) |
Challenge
Check that the number of disks is between 1 and 6 before starting.
Show hint
Put a Repetir ... Hasta Que around the Leer n.
Related examples
Merge Sort
Splits the array in halves, sorts each one recursively and merges them.
AdvancedQuicksort
Picks a pivot, splits smaller from larger values and sorts each side recursively.
AdvancedBy Reference and by Value
Sorts three numbers by swapping them in subprocesses.
Intermediate