Tower of Hanoi recursive and non-recursive algorithm

Tower of Hanoi recursive and non-recursive algorithm

Towers of Hanoi problem is described as follows:

有 A、B、C 3 根针,n 个圆盘(从 1..n )从上到下,按小到大顺序放在 A 处,要求每次移动一个,并保持从小到大的叠放顺序,
利用 C,把 n 个盘子移动到 B 处。

Recursive algorithm

Recursive algorithm easier to understand

fn hanoi(n):
    hanoi_move(n, 'A', 'B', 'C')

fn hanoi_move(n, from, to, medium):
    if n <= 0:
        return
    hanoi_move(n-1, 'A', 'C', 'B')
    println("move {} from {} to {}", n, from, to);
    hanoi_move(n-1, 'C', 'B', 'A')

Non-recursive algorithm

Rethink the entire movement, in the processing from A to B when n, n-1 need to deal discs thereon from A to C, A at the left until a number n of disks, this step is defined for the Step:

struct Step {
    n, r, from, to, medium
}

n r represents the current number is further placed thereon how many discs, when ris 1, can move the disc number n, namely:

Step(n, r, from, to, medium) 分解为
1. Step(r-1, r-1, from, medium, to)
2. Step(n, 1, from, to, medium)
3. Step(r-1, r-1, medium, to, from)

May utilize a bidirectional stack or queue holds intermediate state, until decomposition is complete, the noted opposite direction to the direction of decomposition during storage with a stack:

fn hanoi_move_stack(n, from, to, medium):
    if n <=0:
        return
    s = Stack()
    s.push(Step(n, n, from, to, medium)):
    while !s.is_empty():
        step = s.pop()
        if step.r == 1:
            println("move {} from {} to {}", step.n, step.from, step.to)
        else:
            s.push(Step(step.r-1, step.r-1, step.medium, step.to, step.from))
            s.push(Step(step.n, 1, step.from, step.to, step.medium))
            s.push(Step(step.r-1, step.r-1, step.from, step.medium, step.to))

Guess you like

Origin www.cnblogs.com/fengyc/p/11735845.html