// This program solves the n queens problem using recursive backtracking. // The program will find and print all possible solutions. import java.util.*; public class Queens { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Size? "); int size = console.nextInt(); Board board = new BoardFrame(size); solve(board); } // prints all possible solution to the n-queens problem // pre: solution is an empty board of the correct size public static void solve(Board solution) { explore(solution, 1); } // attempts to place a queen in all possible locations in column col, // recursively checking for solutions using each placement // pre: queens have been safely placed in columns 1 through (col - 1) private static void explore(Board solution, int col) { // if n queens placed if (col > solution.size()) { // we win!! print it. solution.print(); } else { // for each possible move for (int row = 1; row <= solution.size(); row++) { // if move is valid if (solution.safe(row, col)) { // make the move solution.place(row, col); // try the rest of the board explore(solution, col + 1); // undo the move solution.remove(row,col); } } } } }