/* nqueens_prolog.pl */

queens1(N, L) :-                %  enumere N^N cas
    length(L,N),
    enum(L,N),
    check_constrain_all(L).

enum([],_).
enum([X|L],N):-
	enum1(X,1,N),
	enum(L,N).
enum1(X,X,_).
enum1(X,L,N):-
	L < N,
	L1 is L +1,
	enum1(X,L1,N).

check_constrain_all([]).
check_constrain_all([X|Xs]) :-
     constrain_between(X, Xs, 1),
     check_constrain_all(Xs).

constrain_between(_X, [], _N).
constrain_between(X, [Y|Ys], N) :-
     no_threat(X, Y, N),
     constrain_between(X, Ys, N+1).

no_threat(X, Y, I) :-
        X   \= Y,
        XI is X+I,
        XI \= Y,
        X_I is X-I,
        X_I \= Y.
/*
| ?- queens1(8,L).     

L = [1,5,8,6,3,7,2,4] ? 

(9586 ms) yes
| ?- 

 */
