forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 39
/
nQueuens.II.cpp
76 lines (57 loc) · 1.83 KB
/
nQueuens.II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Source : https://oj.leetcode.com/problems/n-queens-ii/
// Author : Hao Chen
// Date : 2014-08-22
/**********************************************************************************
*
* Follow up for N-Queens problem.
*
* Now, instead outputting board configurations, return the total number of distinct solutions.
*
*
**********************************************************************************/
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int totalNQueens(int n);
void solveNQueensRecursive(int n, int currentRow, vector<int>& solution, int& result);
bool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn);
int totalNQueens(int n) {
int result=0;
vector<int> solution(n);
solveNQueensRecursive(n, 0, solution, result);
return result;
}
// the solution is same as the "N Queens" problem.
void solveNQueensRecursive(int n, int currentRow, vector<int>& solution, int& result) {
for (int i = 0; i < n; i++) {
if (isValid(i, currentRow, solution) ) {
if (currentRow+1 == n){
result++;
continue;
}
solution[currentRow] = i;
solveNQueensRecursive(n, currentRow+1, solution, result);
}
}
}
bool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn) {
for(int i=0; i<attemptedRow; i++) {
if (attemptedColumn == queenInColumn[i] ||
abs(attemptedColumn - queenInColumn[i]) == abs(attemptedRow - i)) {
return false;
}
}
return true;
}
int main(int argc, char** argv)
{
int n = 8;
if (argc>1){
n = atoi(argv[1]);
}
int result = totalNQueens(n);
cout << n << " Queens, total = " << result << endl;
return 0;
}