Exercise #3: Solve The Eight Queens Puzzle

◀ The Game of Nim - Step 4▶ Solve The Eight Queens Puzzle - Step 1
Amazon Some of you probably have heard of this famous puzzle. You have an 8-by-8 square board and you have 8 queens. You place them on the board so that none of the queens is able to conflict with another queen. In chess, a queen can move horizontally, vertically, and diagonally for however many units. So basically you make sure they cannot attack each other. Now that you have enough information, go ahead and write a program to solve this puzzle. You need to find all solutions possible, not just one. Here are the suggested specifications for the program:
  • User runs the program with no argument in command line.
  • The program outputs all the solutions onto screen like the following (X is a queen).
Solution: 1
*01234567* 0X 0 1 X 1 2 X2 3 X 3 4 X 4 5 X 5 6 X 6 7 X 7 *01234567* Solution: 2 *01234567* 0X 0 1 X 1 2 X2 3 X 3 4 X 4 5 X 5 6 X 6 7 X 7 *01234567* . . . Solution: 12 *01234567* 0 X 0 1 X 1
2 X 2 3 X 3 4 X4 5X 5 6 X 6 7 X 7 *01234567*
In fact, I’d like the program to be flexible. Your program needs to be able to deal with square boards of every size, not just 8-by-8. You specify it in your program and compile and run it to get the corresponding results.

For example if you specify the board size to be 10-by-10, that means there are ten queens waiting to be placed on the board, and your program finds solutions to it.

You can make it so that user decides the board size in command line, but that is a trivial modification. Ready to roll? Let’s solve the eight queens’ puzzle by applying the Four Step Programming Model described in Chapter 11.8!
◀ The Game of Nim - Step 4▶ Solve The Eight Queens Puzzle - Step 1

fShare
Questions? Let me know!