1.解决6X6 与9X9数独问题。
扩展原例子4X4的数独,重复写行、列、格子太麻烦了,直接贴4X4的例子:
:- use_module(library(clpfd)).
valid([]).
valid([Head|Tail]) :-
all_different(Head),
valid(Tail).
sudoku(Puzzle, Solution) :-
Solution = Puzzle,
Puzzle = [S11, S12, S13, S14,
S21, S22, S23, S24,
S31, S32, S33, S34,
S41, S42, S43, S44],
Puzzle ins 1..4,
Row1 = [S11, S12, S13, S14],
Row2 = [S21, S22, S23, S24],
Row3 = [S31, S32, S33, S34],
Row4 = [S41, S42, S43, S44],
Col1 = [S11, S21, S31, S41],
Col2 = [S12, S22, S32, S42],
Col3 = [S13, S23, S33, S43],
Col4 = [S14, S24, S34, S44],
Square1 = [S11, S12, S21, S22],
Square2 = [S13, S14, S23, S24],
Square3 = [S31, S32, S41, S42],
Square4 = [S33, S34, S43, S44],
valid([Row1, Row2, Row3, Row4,
Col1, Col2, Col3, Col4,
Square1, Square2, Square3, Square4]),
writeln(Row1),
writeln(Row2),
writeln(Row3),
writeln(Row4).
2.采用一个皇后列表的方式解决八皇后问题,使用1~8范围内的数字代表每个皇后,通过皇后列表中的位置取其行号并通过其在列表的值取其列号。
PS.不知道怎么取表中位置,用index代替下表
:- use_module(library(clpfd)).
valid_col([]).
valid_col([Col|Tail]) :-
member(Col, [1, 2, 3, 4, 5, 6, 7, 8]),
valid_col(Tail).
diags1([], [], []).
diags1([Row|RowsTail], [Col|ColsTail], [Diagonal|DiagonalTail]) :-
Diagonal is Row - Col,
diags1(RowsTail, ColsTail, DiagonalTail).
diags2([], [], []).
diags2([Row|RowsTail], [Col|ColsTail], [Diagonal|DiagonalTail]) :-
Diagonal is Row + Col,
diags2(RowsTail, ColsTail, DiagonalTail).
eight_queens(Cols) :-
Cols = [_, _, _, _, _, _, _, _],
valid_col(Cols),
ColIndex = [1, 2, 3, 4, 5, 6, 7, 8],
diags1(ColIndex, Cols, Diags1),
diags2(ColIndex, Cols, Diags2),
all_different(Cols),
all_different(Diags1),
all_different(Diags2).