Skip to content

08.06. Hanota

Description

In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:

(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.

Write a program to move the disks from the first tower to the last using stacks.

Example1:


 Input: A = [2, 1, 0], B = [], C = []

 Output: C = [2, 1, 0]

Example2:


 Input: A = [1, 0], B = [], C = []

 Output: C = [1, 0]

Note:

  1. A.length <= 14

Solutions

Solution 1: Recursion

We design a function $dfs(n, a, b, c)$, which represents moving $n$ disks from $a$ to $c$, with $b$ as the auxiliary rod.

First, we move $n - 1$ disks from $a$ to $b$, then move the $n$-th disk from $a$ to $c$, and finally move $n - 1$ disks from $b$ to $c$.

The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
        def dfs(n, a, b, c):
            if n == 1:
                c.append(a.pop())
                return
            dfs(n - 1, a