// Allison Obourn // CSE 143 - lecture 18 // 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) { solveQueens(b, 1); } // Searches the board for a solution to the n-queens problem starting at // col. Stores a solution in b if it exists. // Pre: col > 0 // Pre: the previous col - 1 queens are correctly placed private static void solveQueens(Board b, int col) { if(col > b.size()) { System.out.println(b); } else { for(int row = 1; row <= b.size(); row++) { if(b.isSafe(row, col)) { b.place(row, col); solveQueens(b, col + 1); b.remove(row, col); } } } } }