皇后区统治

时间:2013-08-02 02:45:53

标签: prolog n-queens

女王统治 给定n×n板,控制数是攻击或占据每个方块所需的最小数量的皇后(或其他部分)。对于n = 8,女王的统治数字是5。 写一个谓词slution(N),以获得覆盖所有正方形所需的最小数量的皇后。

1 个答案:

答案 0 :(得分:4)

这是一个愚蠢的'所有解决方案'片段:

queens_coverage(N, Places) :-
    findall(X/Y, (between(1,N,X), between(1,N,Y)), B),
    placement(B, [], Places).

placement([], Placement, Placement).
placement(Unplaced, SoFar, Placement) :-
    select(Place, Unplaced, Places),
    remove_attacks(Place, Places, Remains),
    placement(Remains, [Place|SoFar], Placement).

remove_attacks(X/Y, [U/V|Places], Remains) :-
    ( U == X ; V == Y ; abs(U-X) =:= abs(V-Y) ),
    !, remove_attacks(X/Y, Places, Remains).
remove_attacks(P, [A|Places], [A|Remains]) :-
    remove_attacks(P, Places, Remains).
remove_attacks(_, [], []).

与排列问题一样,该代码无效率无效:

?- setof(L-Ps, (queens_coverage(4,Ps),length(Ps,L)), R), length(R, T).
R = [3-[1/1, 2/3, 4/2], 3-[1/1, 2/4, 3/2], 3-[1/1, 2/4, 4/3], 3-[1/1, 3/2, 2/4], 3-[1/1, 3/4, ... / ...], 3-[1/1, ... / ...|...], 3-[... / ...|...], 3-[...|...], ... - ...|...],
T = 144.

?- setof(L-Ps, (queens_coverage(5,Ps),length(Ps,L)), R), length(R, T).
R = [3-[1/1, 2/4, 4/3], 3-[1/1, 3/4, 4/2], 3-[1/1, 3/4, 5/3], 3-[1/1, 3/5, 4/3], 3-[1/1, 4/2, ... / ...], 3-[1/1, ... / ...|...], 3-[... / ...|...], 3-[...|...], ... - ...|...],
T = 2064.

?- setof(L-Ps, (queens_coverage(6,Ps),length(Ps,L)), R), length(R, T).
R = [4-[1/1, 2/3, 3/6, 6/2], 4-[1/1, 2/3, 6/2, 3/6], 4-[1/1, 2/4, 4/5, 5/2], 4-[1/1, 2/4, 4/5, ... / ...], 4-[1/1, 2/4, ... / ...|...], 4-[1/1, ... / ...|...], 4-[... / ...|...], 4-[...|...], ... - ...|...],
T = 32640.

?- setof(L-Ps, (queens_coverage(7,Ps),length(Ps,L)), R), length(R, T).
ERROR: Out of global stack

当然,存储所有列表真是浪费。

?- integrate(min, qc(7), R).
R = 4-[1/2, 2/6, 4/1, 5/5] .

?- integrate(min, qc(8), R).
R = 5-[1/1, 2/3, 3/5, 4/2, 5/4] 

而不是select / 3,您应该应用适当的启发式。一个简单的选择可能是贪婪的选择...

修改

这里是整合:

integrate(min, Goal, R) :-
    State = (_, _),
    repeat,
    (   call(Goal, V),
        arg(1, State, C),
        ( ( var(C) ; V @< C ) -> U = V ; U = C ),
        nb_setarg(1, State, U),
        fail
    ;   arg(1, State, R)
    ),
    !.

nb_setarg / 3是内置的SWI-Prolog,arg / 3是ISO。如果您的Prolog错过了它们,您应该使用assert / retract替换 - 例如 -

Integrate接受一个谓词,并使用附加参数调用它与存储的当前最小值进行比较:这里是:

qc(N, L-Ps) :- queens_coverage(N,Ps),length(Ps,L).

至于贪婪的启发式,第二个放置条款可以用

代替
placement(Unplaced, SoFar, Placement) :-
    integrate(min, peek_place_of_min_remain(Unplaced), (_Count,Place,Remains)),
    !, placement(Remains, [Place|SoFar], Placement).

peek_place_of_min_remain(Unplaced, (Count,Place,Remains)) :-
    select(Place, Unplaced, Places),
    remove_attacks(Place, Places, Remains),
    length(Remains, Count).