Skip to content

Instantly share code, notes, and snippets.

@junjihashimoto
Created March 24, 2014 15:37
Show Gist options
  • Save junjihashimoto/9742703 to your computer and use it in GitHub Desktop.
Save junjihashimoto/9742703 to your computer and use it in GitHub Desktop.
knight's tour
import Debug.Trace
import Control.Monad
import qualified Data.Map as M
import qualified Data.Set as S
--tr a b = trace (a++show b) b
tr a b = b
flat=foldl (++) []
board=S.fromList $ flat $ map (\a -> map (\b -> (a,b)) [0..7]) [0..7]
mov=[(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(1,-2),(2,-1)]
mov' (x,y)=map (\(x',y')->(x+x',y+y')) mov
nboard board pos=if S.member pos board
then [(pos,S.delete pos board)]
else []
knight=knight' (S.delete (0,0) board) (0,0)
knight' board pos
|board == S.empty = [[pos]]
|otherwise =
let n = tr "n:" $ flat $ map (nboard board) $ mov' pos
in tr "knight':" $ flat $ map (\(p,b)->map (pos:) (knight' b p)) n
main=do
let res = head knight
let v = zip [0..] res
forM_ [0..7] $ \x->do
forM_ [0..7] $ \y->do
let t=head $ filter ((==(x,y)).snd) v
putStr $ show $ fst t
putStr " "
putStr "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment