King Fahd University of Petroleum & Minerals - Home Page Information & computer Sciences Department

ICS 353

Design & Analysis of Algorithms

Fall 2007 

Home

What's New

Assignments

Quizzes

Handouts

Exams

Covered Topics

Links

 

 

 

The applet here finds all or only the unique solutions for the n queens problem. However, it is too slow for large n, so don't even try it!. It uses conventional backtracking algorithm.

Mathematically, the n queens problem can be stated as follows. A solution for the n queens problem is a permutation sigma() of ( 1 ... n ), such that for any i != j, the following two conditions are true.

n # Solutions # Unique Solutions
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
10
4
40
92
352
724
2,680
14,200
73,712
365,596
2,279,184
14,772,512
95,815,104
666,090,624
4,968,057,848
39,029,188,884
1
2
1
6
12
46
92
341
1,787
9,233
45,752
285,053
1,846,955
11,977,939
83,263,591



sigma( i ) - i != sigma( j ) - j
sigma( i ) + i != sigma( j ) + j

However, you can think of it in a different way. Consider n by n chess board. 

The goal is to place n queens on the board so that no two queens are on the same row, column, or diagonal. The problem is a constraint satisfaction one. When n is eight, i.e., a normal chess board is used, the problem is known as the eight queens problem. Most of the constraint satisfaction problems belong to NP-hard problems, for which no efficient solving methods are known. The n queens problem is one of NP-hard problems, and it has been using as an example in AI research or programming.

Finding a solution to the n Queens problem for any n greater than or equal to 4 can be done without searching. Determining where each queen should go can be done in constant time per queen, or O(n) altogether. Thus, drawing the board (which is O(n^2)) is the rate limiting step. This is demonstrated by the Java applet above.

Note that for a certain n, not all the solutions are unique, i.e. some of them are reflected (around some axis) or rotated from others. See the table for some stat. 

One of the the algorithms that solve it can be found in the ACM SIGART Bulletin, 2(2), page 7. Other different views for the problem can be found in this link.