// 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(); } // prints all solutions to place n-queens on the board public static void solve(Board b) { solve(b, 1); } // Assumes that we have successfully placed col - 1 queens in the previous columns // Prints all solutions to place n-queens on the board private static void solve(Board b, int col) { if (col == b.size() + 1) { // Success b.print(); } else { // In-Bounds Case for (int row = 1; row <= b.size(); row++) { if (b.safe(row, col)) { b.place(row, col); solve(b, col + 1); b.remove(row, col); } } } } }