Skip to content

Instantly share code, notes, and snippets.

@lpand
Created January 29, 2014 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpand/8685806 to your computer and use it in GitHub Desktop.
Save lpand/8685806 to your computer and use it in GitHub Desktop.

image

Exercise 2

Implement a recursive procedure (function/class, you choose) that answers to the eight-queens puzzle problem.

The eight-queens puzzle asks how to place eight queens on a chessboard so that no queen is in check from any other (i.e., no two queens are in the same row, column, or diagonal).

Spoiler: one possible solution

One possible solution is shown in figure 2.8. One way to solve the puzzle is to work across the board, placing a queen in each column. Once we have placed k - 1 queens, we must place the kth queen in a position where it does not check any of the queens already on the board. We can formulate this approach recursively: Assume that we have already generated the sequence of all possible ways to place k - 1 queens in the first k - 1 columns of the board. For each of these ways, generate an extended set of positions by placing a queen in each row of the kth column. Now filter these, keeping only the positions for which the queen in the kth column is safe with respect to the other queens. This produces the sequence of all ways to place k queens in the first k columns. By continuing this process, we will produce not only one solution, but all solutions to the puzzle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment