import java.io.*; /** * NQueens class: an object for a chess board for the N-Queens problem. * It solves itself with the solve() method and displays its output by * outputting to the console and by writing its result to a file.
*
* The AI keyword for this bad boy is Depth-First Search * * @author Darnell Arford * @version 1.0 */ public class NQueens{ private int n; // size of one dimension of the chess board private boolean solved; private int[] col; // tell which row a piece is placed in the column at [index], -1 if none private boolean[] bDiagClear; // tell whether a piece is in a certain diagonal from top left to bottom right private boolean[] fDiagClear; // " " from top right to bottom left // An array is not needed to tell if there is a conflict in a row because the algotithm always // advances to the next row after placing a piece in a row. public NQueens(int size){ n = size; // this is n, the number of queens to solve for solved = false;// keeps track of whether a solution was found col = new int[size]; bDiagClear = new boolean[2*size - 1]; fDiagClear = new boolean[2*size - 1]; for(int i=0; iThis solution was found with a recursive depth-first search.
"); if(time==0){ s = s.concat("It took less than a millisecond to find this solution"); }else{ s = s.concat("It took "); if(hours>0){ s = s.concat(hours + " hours "); } if(minutes>0){ s = s.concat(minutes + " minutes "); } if(seconds>0){ s = s.concat(seconds + " seconds "); } if(millis>0){ s = s.concat(millis + " milliseconds "); } s = s.concat(" to find this solution."); } s = s.concat(""); return s; } /********************************************************************** * MAIN METHOD: RUN THIS TO RUN THE PROGRAM AND GET RESULTS! * @param args[0] The number of queens to solve for */ public static void main(String[] args){ int size; // number of queens try{ size = java.lang.Integer.parseInt(args[0]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("You have to enter an integer argument equal to the number of queens"); return; } NQueens nq = new NQueens(size); long start = System.currentTimeMillis(); boolean foundSolution = nq.solve(); long tot_time = System.currentTimeMillis() - start; nq.print(); nq.writeToFile(tot_time); System.out.println("\nTotal time to complete: " + tot_time + " milliseconds"); } // main() }// NQueens class