forked from jnozsc/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN-Queens_II.cpp
65 lines (61 loc) · 2.27 KB
/
N-Queens_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
/*
Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions.
Example
For n=4, there are 2 distinct solutions.
*/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
int allsolutions = 0;
vector<int> currentSolution;
solveNQueensDFS(allsolutions, currentSolution, 0, n);
return allsolutions;
}
void solveNQueensDFS(int& allsolutions,
vector<int> currentSolution,
int currentLevel, int level) {
// fill in finish, output
if (currentLevel == level) {
allsolutions++;
return;
}
// not finish yet.
for (int i = 0; i < level; i++) {
// if it is emtpy or i is in diffent column
if (currentSolution.empty() || isValid(currentSolution, i)) {
currentSolution.push_back(i);
solveNQueensDFS(allsolutions, currentSolution, currentLevel + 1, level);
currentSolution.pop_back();
}
}
}
bool isValid(vector<int> currentSolution, int newPostion) {
bool flag_column = find(currentSolution.begin(), currentSolution.end(), newPostion) == currentSolution.end();
if (flag_column == false) {
return false;
}
vector<int> diagonal_one, diagonal_two;
for (int i = 0; i < currentSolution.size(); i++) {
diagonal_one.push_back(i + currentSolution[i]);
diagonal_two.push_back(i - currentSolution[i]);
}
bool flag_diagonal_one = find(diagonal_one.begin(), diagonal_one.end(), currentSolution.size() + newPostion) == diagonal_one.end();
if (flag_diagonal_one == false) {
return false;
}
bool flag_diagonal_two = find(diagonal_two.begin(), diagonal_two.end(), currentSolution.size() - newPostion) == diagonal_two.end();
if (flag_diagonal_two == false) {
return false;
}
return true;
}
};