The Tower of Hanoi (also called The problem of Benares Temple[1] or Tower of Brahma or Lucas’ Tower[2] and sometimes pluralized as Towers, or simply pyramid puzzle[3]) is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters, which can slide onto any rod. The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top, thus approximating a conical shape. The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules:

  1. Only one disk may 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 or on an empty rod.
  3. No disk may be placed on top of a disk that is smaller than it.

Prints n moves in the Tower of Hanoi puzzle.

func tower_of_hanoi(_ n: Int) -> [[Int]] {
    var result: [[Int]] = []
    
    func helper(_ n: Int, _ src: Int, _ aux: Int, _ dst: Int) {
        if n == 1  {
            result.append([src, dst])
            return
        }
        
        helper(n - 1, src, dst, aux)
        result.append([src, dst])
        helper(n - 1, aux, src, dst)
    }
    
    helper(n, 1, 2, 3)
    
    return result
}

print(tower_of_hanoi(3))

Leave a Reply