// Marty Stepp, CSE 143, Winter 2009 // This program solves the classic "8 queens" problem using recursive // backtracking. import java.util.*; public class Queens { public static void main(String[] args) { Board b = new GraphicalBoard(8); solveQueens(b); } // Solves the eight queens problem on the given board. // Precondition: board is of size 8 public static void solveQueens(Board b) { solveQueens(b, 0); } // Recursive helper to solve the eight queens problem on the given board. // Precondition: The given number 'count' of queens are already placed private static void solveQueens(Board b, int count) { if (count == 8) { // base case: all queens are placed; print board System.out.println(b); } else { // recursive case: loop through all squares, looking for a // place to put one queen for (int row = 1; row <= 8; row++) { for (int col = 1; col <= 8; col++) { if (b.isSafe(row, col)) { b.place(row, col); // make a choice solveQueens(b, count + 1); // explore the rest b.remove(row, col); // un-make the choice } } } } } }