(* i need to know which are the accessible
cases from any position of the knight *)
let destinations (a,b) = (a-2,b-1) :: (a-2,b+1) ::
(a-1,b-2) :: (a-1,b+2) ::
(a+1,b-2) :: (a+1,b+2) ::
(a+2,b-1) :: (a+2,b+1) :: []
let legal (n,p) (a,b) = (0 <= a) && (a < n) && (0 <= b) && (b < p) ;;
let legal_destinations dim pos =
let rec aux l = match l with
| t::q -> if (legal dim t) then (t::(aux q)) else aux q
| _ -> []
in aux (destinations pos)
(* two small useful functions *)
let set mat (a,b) value = mat.(a).(b) <- value
let get mat (a,b) = mat.(a).(b)
(* finally... *)
let chess n p =
let board = Array.make_matrix n p 0 in
set board (0,0) 1 ;
let rec aux pos check =
if check = (n * p) then true else
let rec aux2 l = match l with
| t::q when 0 = get board t -> (set board t (check+1) ; aux t (check+1))
|| (set board t 0 ; aux2 q)
| t::q -> aux2 q
| _ -> false
in aux2 (legal_destinations (n,p) pos)
in let okay = aux (0,0) 1 in
if okay then board else [|[|-1|]|]
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.