Professional Documents
Culture Documents
Lab 3 N - Queens Problem in Prolog
Lab 3 N - Queens Problem in Prolog
To solve N-Queens problem let us first discuss solution to eight queens’ problem.
1. The eight queen’s problem: The problem here is to place eight queens on the empty
chessboard in such a way that no queen attacks any other queen. A queen can perform
horizontal, vertical or diagonal attack.
1.1 Solution 1: The board position of the queens is represented by their Y-coordinates (i.e.
[Y1, Y2, Y3, …, Y8] since to prevent the horizontal attack no two queens cann be in the same
row. Each solution is represented as permutation of the list [1,2,3,4,5,6,7,8]. The program is
listed below:
Solution 1
solution(Queens) :-
permutaion([1,2,3,4,5,6,7,8], Queens),
safe(Queens).
permutation([], []).
permutation([Head|Tail], PermList) :-
permutation(Tail, PermTail),
del(Head, PermList, PermTail). % Here insert Head in permuted Tail
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]
).
2. The N queen’s problem: The problem here is to place N queens on the empty N x N size
chessboard in such a way that no queen attacks any other queen.
2.1 Solution 1: Use the solution 1 given for eight queens problem to solve N queens
problem.
2.2 Solution 2: Use the solution 2 given for eight queens problem to solve N queens
problem.
(Hint: For both you need a procedure gen(N1, N2, List) which will, for two given intergers
N1 and N2, produces the list: List = [N1, N1 + 1, N1 + 2, …., N2 -1, N2]. For solution 2 you
need to define solution(N,S) where N is the size of board, and S is a solution represented as
a list of Y-coordinates of N queens)
3. Compare the time taken by each solution when you take 8, 16, 32 and 64 queens and
complete the following table.
Queens Time taken by
Solution 1 Solution 2
8
16
32
64