Reve的拼图递归解决方案

时间:2015-09-13 21:44:39

标签: algorithm haskell recursion functional-programming

经典tower of hanoi问题在haskell中有非常优雅的解决方案:

type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 0 _ _ _ = []
hanoi n from to via = (hanoi (n - 1) from via to) ++ [(from, to)] ++ (hanoi (n - 1) via to from)

我努力为四个钉子(也称为Reve'难题)寻找同一问题的解决方案,尽可能少的动作。

众所周知,三个钉子的最小步骤量是2 ^ n-1。对于15个磁盘它是32676,而对于四个磁盘,它只有cis194 homework#1 ex. 6中提到的129个磁盘。以下是我对该任务的看法:

hanoiiii :: Integer -> Peg -> Peg -> Peg -> Peg -> [Move]
hanoiiii n from to via1 via2
  | n == 0 = []
  | n == 1 = [(from, to)]
  | n == 3 = [(from, via1), (from, via2), (from, to), (via2, to), (via1, to)]
  | otherwise = (hanoiiii (n - 1) from via1 to via2) ++ [(from, to)] ++ (hanoiiii (n - 1) via1 to from via2)
  

长度$ hanoiiii 15" a" " B" " C" " d"

     

24575

正如你所看到的那样,即使工作也不是最理想的。请帮我找到合适的解决方案。

0 个答案:

没有答案