// CSE 143, Winter 2012 // This program solves the classic "8 queens" problem using recursive // backtracking. 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: b != null public static void solveQueens(Board b) { explore(b, 1); System.out.println(b); } // Precondition: queens have been safely placed in columns 1 to col - 1 // Recursive private helper that searches the board for a solution starting // at col. If there is a solution, return true and store the solution in // Board b, otherwise return false. private static boolean explore(Board b, int col) { if (col > b.size()) { return true; // all queens have been safely placed } else { // for each of my choices: for (int row = 1; row <= b.size(); row++) { // choose if (b.isSafe(row, col)) { b.place(row, col); // explore if (explore(b, col + 1)) { return true; } // unchoose b.remove(row, col); } } } return false; } }