Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution {
public:
void print(int queue[], int n, vector<vector<string>> &qipan) {
int i, j;
/*for(i = 0; i < n; i++) {
printf("row :%d, col :%d\n", i , queue[i]);
} */
vector<string> method;
for(i = 0; i < n; i++) {
string str(n,'.');
str[queue[i]] = 'Q';
method.push_back(str);
}
//printf("\n");
qipan.push_back(method);
//printf("\n");
}
void testQueue(int queue[], int row, int n, vector<vector<string>> &qipan) {
int j, k;
if(row >= n) print(queue, n, qipan);
else {
for(j = 0; j < n; j++) {
queue[row] = j;
for(k = 0; k < row; k++) {
if((queue[k] - queue[row]) * (fabs(queue[k] - queue[row]) - fabs(k - row)) == 0) {
break;
}
if(k == row - 1) testQueue(queue, row + 1, n, qipan);
}
}
}
}
int totalNQueens(int n) {
vector<vector<string>> qipan;
int queue[n];
int i;
for(i = 0; i < n; i++ ) queue[i] = -1;
for(i = 0; i < n; i++) {
//printf("method :\n");
queue[0] = i;
testQueue(queue, 1, n, qipan);
}
return qipan.size();
}
};