// This program solves the classic "8 queens" problem using recursive // backtracking, printing all solutions. import java.util.*; public class Queens { 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(); 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(); } // Solves the n-queens problem using the given board, // prints out all possible ways of arranging n queens // on the board such that none can attack each other // where n is the size of the board. public static void solve(Board b) { explore(b, 1); } // pre: b != null, 0 < col <= b.size() + 1 // each column from 1 to col - 1 is valid // explores every possible way of placing a // queen in the given column and the rest of // the board after this column such that they are valid // placements. If col > b.size(), then the board is // fully placed and the solution is printed private static void explore(Board b, int col) { // base case if (col == b.size() + 1) { b.print(); } else { // recursive case // for each choice: each possible row in this col for (int row = 1; row <= b.size(); row++) { // important to check to make sure our precondition holds // for the next recursive call if (b.safe(row, col)) { b.place(row, col); // choose explore(b, col + 1); // explore b.remove(row, col); // unchoose } } } } }