// CSE 143, Winter 2011, Marty Stepp // This program solves the classic "8 queens" problem using recursive // backtracking. // // This file isn't quite correct, because it doesn't stop when it places // the 8th queen. We will fix it during Monday's lecture. // (A correct version of the code can be found in your section handout.) 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) { solveQueens(b, 1); } // Solves the eight queens problem on the given board, starting from the // given column, assuming that any previous columns are already safely // placed. private static boolean solveQueens(Board b, int column) { if (column > b.size()) { return true; // base case: already placed all queens safely } else { // assumes that all prior columns have already been placed safely for (int row = 1; row <= 8; row++) { if (b.isSafe(row, column)) { b.place(row, column); // choose if (solveQueens(b, column + 1)) { // explore return true; } b.remove(row, column); // un-choose } } return false; } } }