// Stuart Reges // 12/7/98 // // This program solves the classic "8 queens" problem using recursive // backtracking. import java.util.*; public class BadQueens { public static void main(String[] args) { giveIntro(); Scanner console = new Scanner(System.in); System.out.print("What size board do you want to use? "); int size = console.nextInt(); while (size != 4) { System.out.println("Sorry not sorry, I can only do size 4 right now."); System.out.print("What size board do you want to use? "); size = console.nextInt(); } System.out.println(); Board b = new Board(size); solve(b); } // post: explains program to user public static void giveIntro() { System.out.println("This program solves the classic '8 queens'"); System.out.println("problem, placing queens on a chessboard so"); System.out.println("that no two queens threaten each other."); System.out.println(); } // post: searches for a currentBoard to the 8 queens problem with this // board, reporting result. /* * place(row,row) * remove(row,row) * safe(row,row) */ public static void solve(Board currentBoard) { // place a queen on the first row for (int row = 1; row <= currentBoard.size(); row++) { if (currentBoard.safe(row, 1)) { currentBoard.place(row, 1); // choose for (int otherRow = 1; otherRow <= currentBoard.size(); otherRow++) { // explore if (currentBoard.safe(otherRow, 2)) { currentBoard.place(otherRow, 2); // choose for (int otherOtherRow = 1; otherOtherRow <= currentBoard.size(); otherOtherRow++) { // explore if (currentBoard.safe(otherOtherRow, 3)) { currentBoard.place(otherOtherRow, 3); // choose for (int otherOtherOtherRow = 1; otherOtherOtherRow <= currentBoard.size(); otherOtherOtherRow++) { // explore if (currentBoard.safe(otherOtherOtherRow, 4)) { currentBoard.place(otherOtherOtherRow, 4); // choose currentBoard.print(); // we did it!!! System.out.println(); currentBoard.remove(otherOtherOtherRow, 4); // unchoose } } currentBoard.remove(otherOtherRow, 3); // unchoose } } currentBoard.remove(otherRow, 2); // unchoose } } currentBoard.remove(row, 1); // unchoose } } } // our to-be recursive backtracking currentBoard // // pre : currentBoard is a valid partial-solution (no queens can knock another // out of the game), col is the next column to consider // post : finds all solutions by placing queens in the range // [col, currentBoard.size()] private static void solve(Board currentBoard, int col) { if (col > currentBoard.size()) { // we're done } else { // recursively backtrack! } } }