You are on page 1of 2

# BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE

Second Semester 2007-2008
EA C461 Artificial Intelligence
Lab 3: Solving N-Queens Problem in PROLOG
Document Prepared By:

Mukesh Kumar Rohil, CS & IS Group, BITS, Pilani – 333031 (Rajasthan), India
rohil@bits-pilani.ac.in
To solve N-Queens problem let us first discuss solution to eight queens’ problem.

Solution 1

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(Queens) if Queens is a list of Y-coordinates of eight non-attacking queens
solution(Queens) :permutaion([1,2,3,4,5,6,7,8], Queens),
safe(Queens).

Solution 2

1.2 Solution 2: Each queen has to be placed on some square; that is; into some column,
some row, some upward diagonal, and some downward diagonal. So we will consider a richer
representation with four coordinates: x: columns, y:rows, u: upward diagonal, and v: downward
diagonal. The coordinates are not independent: given x and y, u and v can be computed as u = x
–y, v = x + y. The domains for all four dimensions are: Dx = [1, 2, 3, 4, 5, 6, 7, 8], Dy = [1, 2, 3,
4, 5, 6, 7, 8], Du = [-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7], and Dv = [2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16]. The program is listed below:
% solution(Queens) if Queens is a list of Y-coordinates of eight non-attacking queens
solution(Ylist) :sol(Ylist,
[1, 2, 3, 4, 5, 6, 7, 8],
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.

pl. and S is a solution represented as a list of Y-coordinates of N queens) 3. 32 and 64 queens and complete the following table. Queens Time taken by Solution 1 Solution 2 8 16 32 64 4. N is number of queens 8 or N.in before 07:00 PM today. For solution 2 you need to define solution(N. and S is solutions number either 1 or 2. produces the list: List = [N1.S) where N is the size of board. N2. . List) which will. N1 + 2. for two given intergers N1 and N2. N1 + 1. Compare the time taken by each solution when you take 8. N2].ac. The four files to zipped as L3_YourIDNo.zip and should emailed at rohil@bits-pilani. N2 -1.no. Name your files as L3_YourIDNo_N_S..(Hint: For both you need a procedure gen(N1. 16. …. where YourIDNo is your 11 character BITS id.