prolog求解八皇后问题

Solution #1:
solution([]).

solution([X/Y|Others]) :-
solution(Others),
member(Y, [1,2,3,4,5,6,7,8]),
noattack(X/Y, Others).

noattack(_,[]).

noattack(X/Y,[X1/Y1|Others]) :-
Y == Y1,
Y1 - Y == X1 - X,
Y1 - Y == X - X1,
noattack(X/Y,Others).

member(Item,[Item|Rest]).

member(Item,[First|Rest]) :-
member(Item,Rest).

template([1/Y1,2/Y2,3/Y3,4/Y4,5/Y5,6/Y6,7/Y7,8/Y8]).
Solution #2:
solution(Queens) :-
permutation([1,2,3,4,5,6,7,8], Queens),
safe(Queens).

permutation([],[]).

permutation([Head|Tail],PermList) :-
permutation(Tail,PermTail),
del(Head,PermList,PermTail).

del(Item,[Item|List],List).

del(Item,[First|List],[First|List1]) :-
del(Item,List,List1).

safe([]).

safe([Queen|Others]) :-
safe(Others),
noattack(Queen,Others,1).

noattack(,[],).

noattack(Y,[Y1|Ylist],Xdist) :-
Y1-Y==Xdist,
Y-Y1==Xdist,
Dist1 is Xdist + 1,
noattack(Y,Ylist,Dist1).
Solution #3:
solution(Ylist) :-
sol(Ylist,[1,2,3,4,5,6,7,8],
[1,2,3,4,5,6,7,8],
[-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7],
[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]).

sol([],[],[],Du,Dv).

sol([Y|Ylist],[X|Dx1],Dy,Du,Dv) :-
del(Y,Dy,Dy1),
U is X-Y,
del(U,Du,Du1),
V is X+Y,
del(V,Dv,Dv1),
sol(Ylist,Dx1, Dy1,Du1,Dv1).

del(Item,[Item|List],List).

del(Item,[First|List],[First|List1]) :-
del(Item,List,List1).

输出:
?- findall(S, solution(S), LS), length(LS,N), write(N).
92

Other
domains %域段,区分不同变量类型的数据
queen=c(integer, integer) %对每一个皇后声明其有两个整数域(所在行和所在列)
list=queen* %定义皇后表list,表中元素都为queen类型。
range=integer* %定义范围表range存储取值范围,表中的数据类型都为整数

predicates %谓词段 用户自定义谓词并说明谓词变元的域
queens(list) %八皇后棋盘
member(integer,range) %取值范围
noconflict(queen,list) %冲突解决
clauses %子句段,由事实与规则构组成
queens([]).%事实,八皇后答案解决表
queens([c(X,Y)|Others]):- %规则,定义为
queens(Others), %其他皇后也满足queens条件
member(Y,[1,2,3,4,5,6,7,8]), %Y的取值只能是1-8
noconflict(c(X,Y),Others). %皇后c与其他成员不冲突

noconflict(,[]). %事实,皇后位置不冲突
noconflict(c(X,Y),[c(X1,Y1)|Others]):- %规则,蕴含
Y<>Y1, %ne(Y,Y1) %不在同一列
Y1-Y<>X1-X, %ne(Y1-Y,X1-X) %不在同一主对角线
Y1-Y<>X-X1, %ne(Y1-Y,X-X1) %不在同一副对角线
noconflict(c(X,Y),Others). %该皇后不与其他皇后冲突
member(X,[X|
]).
member(X,[_|Z]):-
member(X,Z).
goal %求解目标
queens([c(1,A),c(2,B),c(3,C),c(4,D),c(5,E),c(6,F),c(7,G),c(8,H)]). %八个皇后肯定不在同一行,求解各自的列值

你可能感兴趣的:(人工智能)