tower of hanoi - How to not skip over a peg every recursion

前端 未结 1 578
盖世英雄少女心
盖世英雄少女心 2021-01-28 08:29

My assignment is to solve the Towers of Hanoi for any number using recursion. I wrote my code in C++.

Rules:

  1. Cannot stack a larger disk on
相关标签:
1条回答
  • 2021-01-28 09:04

    Basically on each call you need to do the following steps:

    1. Move the n-1 stack of discs to the 4th peg (or 2nd when going backwards)

    2. Move the nth disc to the middle (3rd peg)

    3. Move the n-1 stack back to the 2nd peg (i.e. 4th when going backwards)

    4. Move the nth disc to its destination

    5. Move the n-1 stack to the destination

    So you need 3 recursive calls without memoization.

    function hanoi5(n) {
      let out = []
      move(n, 0, 4)
      console.log(out.length + " steps")
      console.log(out.join("\n"))
      function move(n, from, to) {
        if (n == 1) {
          let dir = from < to ? 1 : -1
          for (let i = from; i != to; i += dir)
            out.push("move disc 1 from peg " + (i+1) + " to peg " + (i+1+dir))
        } else if (from < to) {
          move(n - 1, from, 3)
          for (let i = from; i < 2; i++)
            out.push("move disc " + n + " from peg " + (i+1) + " to peg " + (i+2))
          move(n - 1, 3, 1)
          for (let i = 2; i < to; i++)
            out.push("move disc " + n + " from peg " + (i+1) + " to peg " + (i+2))
          move(n - 1, 1, to)
        } else {
          move(n - 1, 3, 1)
          out.push("move disc " + n + " from peg 3 to peg 2")
          move(n - 1, 1, 3)
          out.push("move disc " + n + " from peg 2 to peg 1")
          move(n - 1, 3, 1)
        }
      }
    }
    
    hanoi5(3)

    0 讨论(0)
提交回复
热议问题