yingpotter

[99p]Knight's Tour

Aug 6th, 2011
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.List
  2. import Data.Function
  3.  
  4. ----- Knight's Tour Function
  5. eightDir :: (Int, Int) -> [(Int, Int)]
  6. eightDir r = [(x -2, y +1),(x -1, y +2),(x -2, y -1),(x -1, y -2),
  7.               (x +2, y -1),(x +1, y -2),(x +2, y +1),(x +1, y +2)]
  8.              where x = fst r
  9.                    y = snd r
  10. knighTour' :: Int -> Int -> [[(Int,Int)]] -> [[(Int,Int)]]
  11. knighTour' n 1 routes = routes
  12. knighTour' n size routes = knighTour' n (size-1) (concatMap stepUp routes)
  13.                            where stepUp route = [ route ++ [s] | s <- sortedaccess (last route)]
  14.                                                 where sortedaccess r = sortBy (compare `on` accessibility) (filter ( \x -> (x `notElem` route) && (inRegion x) ) (eightDir r))
  15.                                                       inRegion x = (fst x >= 1) && (fst x <= n) && (snd x >= 1) && (snd x <= n)
  16.                                                       accessibility x = length $ filter ( \x -> (x `notElem` route) && (inRegion x) ) (eightDir x)
  17. knighTour :: Int  -> [[(Int,Int)]]
  18. knighTour n = knighTour' n (n*n) [[(1,1)]]
Advertisement
Add Comment
Please, Sign In to add comment