Hi all,
I have code that find the solution to a N-queens problem by starting at the upper left hand corner of the board and works its way through the rows and columns. However, I would like to modify the code so that it places a queen at a random place and then starts looking for the solution at that random row and column. Any help is greatly appreciated. Here is the code I have for a four queens problem but it doesnt start with a queen at a random place.
public class EightQueens extends JApplet { public static final int SIZE = 4; // The size of the chess board private int[] queens = new int[SIZE]; // The queen positions public EightQueens() { search(0); // Search for a solution from row 0 add(new ChessBoard(), BorderLayout.CENTER); } /** Check if a queen can be placed at row i and column j */ private boolean isValid(int row, int column) { for (int i = 1; i <= row; i++) if (queens[row - i] == column // Check column || queens[row - i] == column - i // Check upleft diagonal || queens[row - i] == column + i) // Check upright diagonal return false; // There is a conflict return true; // No conflict } /** Search for a solution starting from a specified row */ private boolean search(int row) { if (row == SIZE) // Stopping condition return true; // A solution found to place 8 queens in 8 rows for (int column = 0; column < SIZE; column++) { queens[row] = column; // Place a queen at (row, column) if (isValid(row, column) && search(row + 1)) return true; // Found, thus return true to exit for loop } // No solution for a queen placed at any column of this row return false; }