// This program solves the classic "8 queens" problem using recursive // backtracking. 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(); } // post: searches for a solution to the 8 queens problem with this // board, reporting result. // // where are we going? // how many queens we have left to place // where have we been? // where are queens placed? public static void solve(Board solution) { boolean solved = solve(solution, 1); if (!solved) { System.out.println("No solution found."); } } // // public Board(int size) // // public boolean safe(int row, int col) // public void place(int row, int col) // public void remove(int row, int col) // public int size() // public void print() // // pre: all queens < col are placed and valid // solution.size() == 4 private static boolean solve(Board solution, int col) { if (col > solution.size()) { solution.print(); return true; } else { // try every row from 1 - 8 for (int row = 1; row <= solution.size(); row++) { // is it safe? if (solution.safe(row, col)) { // choose -- a row to place (row, col), (4, col) solution.place(row, col); // explore -- recurse boolean solved = solve(solution, col + 1); if (solved) { return solved; } // unchoose -- take queen off (row, col) solution.remove(row, col); } } return false; } } }