回溯法(backtyacking)渐进地寻找一个备选方案,一旦确定该被选方案不可能是一个有效方案的时候则放弃掉,继而寻找一个新的备选方案。
public class EightQueens { private static final int SIZE = 8; private int[] queens = {-1, -1, -1, -1, -1, -1, -1, -1}; // check if a queen can be placed at row i and column j private boolean isValid(int row, int column) { 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; } private int findPosition(int k) { int start = queens[k] + 1; // search for a new placement for (int j = start; j < SIZE; j++) { if (isValid(k, j)) return j; // (k, j) is the place to put the queen now. } return -1; } public boolean search() { int k = 0; while (k >= 0 && k < SIZE) { int j = findPosition(k); if (j < 0) { queens[k] = -1; k--; } else { queens[k] = j; k++; } } return (k==-1)? false:true; } }附:递归解法
public class EightQueens { private static final int SIZE = 8; private int[] queens = new int[SIZE]; // queen positions. // 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; } private boolean search(int row) { if (row == SIZE) // stop condition return true; // a solution found to place 8 queens in 8 rows. for (int column=0; column<SIZE; column++) { queens[row] = column; // place q queen at (row, column) if (isValid(row, column) && search(row+1)) return true; // found, thus return to exit for loop } // no solution for a queen placed at any column of this row return false; } public boolean search() { return search(0); } }