我的专长!
哈斯克尔代码:
import Control.Monad (guard)
paths (a,b) (a',b') m n = solve [(a',b')] where
solve result@((y,x):_) = do
next@(y',x') <- [(y,x + 1),(y,x - 1),(y + 1,x),(y - 1,x)]
guard (y' >= 0 && y' < m && x' >= 0 && x' < n && notElem (y',x') result)
if next == (a,b) then [(next:result)] else solve (next:result)
输出:
*Main> take 2 . paths (0,3) (3,1) 5 $ 5
[[(0,3),(0,2),(0,1),(0,0),(1,0),(1,1),(1,2),(1,3),(1,4),(2,4),(2,3),(2,2),(2,1),(2,0),(3,0),(4,0),(4,1),(4,2),(4,3),(4,4),(3,4),(3,3),(3,2),(3,1)]
,[(0,3),(0,2),(0,1),(1,1),(1,2),(1,3),(1,4),(2,4),(2,3),(2,2),(2,1),(2,0),(3,0),(4,0),(4,1),(4,2),(4,3),(4,4),(3,4),(3,3),(3,2),(3,1)]]
(0.02 secs, 1595416 bytes)
*Main> length . paths (0,3) (3,1) 5 $ 5
4914
(1.28 secs, 100724732 bytes)
*Main Data.List Data.Ord> minimumBy (comparing length) . paths (0,3) (3,1) 5 $ 5
[(0,3),(1,3),(2,3),(3,3),(3,2),(3,1)]
(1.42 secs, 101955224 bytes)