< Back

Lecture 30 - Backtracking


As usual, create a directory to hold today's activities:

  $ mkdir ~/cs170/labs/lab30 
  $ cd ~/cs170/labs/lab30

N-Queens

Solve It!

conflicts.cc


Backtracking

In Computer Science, we like elegant things. However, sometimes there isn't a real elegant solution. Sometimes, the only real solution is to just try all the solutions! However, sometimes there's a lot of possible solutions to try. Backtracking is a mechanism which is essentially a more directed brute force search. Instead of computing a full solution, you stop trying a solution once you found something that won't work.


N-Queens

In a file called NQueens.cc, create a program that solves the 8-Queens problem. You should create an \(8 \times 8\) 2-dimensional array, initially filled with 0's. You will use the number \(1\) to represent a location with a queen in it.

To solve this problem, you will need AT LEAST 2 helper functions:

You may need helper functions! Don't be afraid to add more!

 

Challenge

Once you finished the code for the 8 Queens problem, modify your code so that it can solve the N-Queens problem. If written properly, this should mean only needing to change one constant value defined at the top of your program.

Attempt to solve the N-Queens problem for board sizes in the range \([1, 25]\). Which ones are solvable? Which ones aren't? At what point do the solutions take an obvious amount of time?