解法:
一行一行地填,
recursive(int start, int end);表示选择从start行到n行的元素
递归结束的条件是:
start == n, 即所有的位置都已经选好了,而且都是符合条件的(不符合条件的话会中途退出)
对于某一行来说,从0到n的位置(从做到右)选它的列坐标
它所在的列不能有皇后,同时它所在的两条对角线上也不能有皇后,如果不满足条件就continue,找下一个看,所有能到下一个环节的每个点都是满足条件的
按要求选好一个位置后,更新相应的辅助数组:isColumnFilled保存的是该列是否已经有皇后,isPosSlantFill保存某条正对角线上是否有皇后, isConSlantFill保存某条反对角线上是否有皇后
然后再n+1行以后的点
完事了撤销当前的选择去寻找更多的可能
它所在的两条对角线上也不能有皇后
如果两个皇后在同一条正对角线:它们的row - column的值是一样的
如果两个皇后在同一条反对角线:它们的row + column的值是一样的
import java.util.*;
import java.lang.*;
public class Solution {
/**
*
* @param n int整型 the n
* @return int整型
*/
int solution = 0;
Set<Integer> isPosSlantFill = new HashSet<Integer>();
Set<Integer> isConSlantFill = new HashSet<Integer>();
public int Nqueen (int n) {
if (n == 1) {
return 1;
}
boolean[] isColumnFilled = new boolean[n];
recursiveFill(0, n, isColumnFilled);
return solution;
}
private void recursiveFill(int currentRow, int n, boolean[] isColumnFilled) {
if (currentRow == n) {
solution += 1;
return ;
}
for (int column = 0; column < n; column++) {
if (isColumnFilled[column] || isPosSlantFill.contains(currentRow - column) ||
isConSlantFill.contains(currentRow + column)) {
continue;
}
isColumnFilled[column] = true;
isPosSlantFill.add(currentRow - column);
isConSlantFill.add(currentRow + column);
recursiveFill(currentRow + 1, n, isColumnFilled);
isColumnFilled[column] = false;
isPosSlantFill.remove(currentRow - column);
isConSlantFill.remove(currentRow + column);
}
}
}

京公网安备 11010502036488号