8 Queens

Chapter: 8 Queens

Backtracking with a stack works very well for small magic square problems. But the exponential nature of backtracking algorithms quickly renders the solution of larger squares intractable. You probably had enough trouble solving the 4*4, let alone the 5*5.

Here is another classical puzzle: Try to place eight queens on a chessboard so that no queen attacks any other. Queens can move any number of spaces along their own row, their own column, or either of the two diagonals that pass through them. The applet below has been deliberately slowed down using

            try {
                Thread.sleep(DELAY);
            }
            catch (InterruptedException ie) {}
after each update. But still it should have a solution by the time you finish reading this paragraph. You may be interested to know that DELAY is set to half a second, so the algorithm itself is pretty fast on an 8*8 chessboard.

            Your browser is ignoring the <APPLET> tag!      

Initially you might have thought this would be a hopelessly slow search involving 64 possible positions (the squares of the chessboard) each with two possibilities (queen or no-queen). This would lead you to fear that a backtracking program would have to search among 2^64 possibilities. That would, as you know, never finish in a million lifetimes.

In fact, the nature of the problem is much friendlier than that.

As you can see, the algorithm works by placing a queen on the top row. Then it tries to place a queen on the second row. Then the third, etc... If it ever places a queen where she is being attacked by a previously placed queen, the algorithm will backtrack.

At worst then, it needs to look at 8 possible positions for a queen on the first row; for each of these there will be 8 (or 7 if you're clever) possibilities on the second, 8 (or 6 if you're clever) on the third, etc.

Even if you're not clever, that's a very manageable search space of size 8^8 or 16,777,216. It turns out there are so many solutions you're going to hit one well before you try 16 million possibilities. And if you're clever, the entire search space has size 8! That's an easily managed 40,320.

Now you can see why I can afford to deliberately slow down my animation.


Exercise 3

Write a backtracking program to solve the n queens problem. (Above is the 8 queens problem. The n queens problem is similar but requires you to place n non-attacking queens on a n*n chessboard.) You may work this entirely on your own; or you may follow the hint and use some code that I provide below.


rhyspj@gwu.edu