题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
解法:
解法同上一篇N皇后问题,这里只要求输出解的个数,本来用全局变量很容易就解决的,不知道为什么Judge系统死命的报错,对已2皇后问题,本地明明输出0,线上偏偏显示1,最后实在没办法,就把count封装金了内部类中,然后就AC了
O_o!
public class No51_NQueensII {
class Pair{
int count;
public Pair(int i){
count = i;
}
}
public static void main(String[] args){
No51_NQueensII m = new No51_NQueensII();
System.out.println(m.totalNQueens(8));
}
public int totalNQueens(int n) {
Pair p = new Pair(0);
if(n > 0){
char[][] element = new char[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
element[i][j] = '.';
solve(p, element, n, 0);
}
return p.count;
}
public static void solve(Pair p, char[][] C, int n, int col){
for(int i=0;i<n;i++){
C[i][col] = 'Q';
if(isLegal(C, i, col)){
if(col == n-1){
p.count++;
C[i][col] = '.';
continue;
}
solve(p, C, n, col+1);
}
C[i][col] = '.';
}
return;
}
public static boolean isLegal(char[][] C, int row, int col){
for(int j=0;j<col;j++){
if(C[row][j] == 'Q')
return false;
}
for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
if(C[i][j] == 'Q')
return false;
}
for(int i=row+1,j=col-1;i<C.length&&j>=0;i++,j--){
if(C[i][j] == 'Q')
return false;
}
return true;
}
}