【原题】
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
【分析】
本题为N皇后问题,要求解的个数
思路是回溯法,一行一行地遍历,每个位置试一下,看能否构成解。
由题目要求,同一行、同一列、同一对角线上不同有两个或以上的皇后,所以需要用到三个标记数组,用来表示这一行或这一列这一对角线上不能有皇后。
这里特别注意对角线上的问题:
- 若在正对角线上(\),假设(x,y)位置有皇后了,则(i,j)位置也不能有皇后,(i,j)满足下列条件:
x-y=i-j - 若在斜对角线上(/),同样假设(x,y)位置有皇后了,则(i,j)位置也不能有皇后,(i,j)满足下列条件:
x+y=i+j
下面看代码实现
【Java】
public class Solution {
int count=0;
public int totalNQueens(int n) {
boolean[] col = new boolean[n];
boolean[] d1 = new boolean[2*n];
boolean[] d2 = new boolean[2*n];
helper(0,col,d1,d2,n);
return count;
}
private void helper(int row, boolean[] col, boolean[] d1,
boolean[] d2, int n) {
if(row==n) count++;
for (int i = 0; i < n; i++) {
int id1 = i+row;
int id2 = n+row-i;
if(col[i]||d1[id1]||d2[id2])
continue;
col[i]=true;d1[id1]=true;d2[id2]=true;
helper(row+1,col,d1,d2,n);
col[i]=false;d1[id1]=false;d2[id2]=false;
}
}
}