// Helene Martin, CSE 143 // This program solves the classic "n queens" problem using recursive // backtracking. import java.util.*; public class Queens { public static void main(String[] args) { 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 GraphicalBoard(size); solveQueens(b); } // Solves the queens problem on the given board. // Precondition: b != null public static void solveQueens(Board b) { if (solveQueens(b, 1)) { System.out.println(b); } else { System.out.println("No solution!"); } } // Searches the board for a solution to the n-queens problem starting at // col. Stores a solution in b if it exists. // pre: the previous col - 1 queens are correctly placed private static boolean solveQueens(Board b, int col) { if (col > b.size()) { return true; } else { for (int row = 1; row <= b.size(); row++) { if (b.isSafe(row, col)) { b.place(row, col); if (solveQueens(b, col + 1)) { return true; } b.remove(row, col); } } return false; } } }