-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queens_II
44 lines (37 loc) · 1005 Bytes
/
N-Queens_II
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
/*
N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
*/
class Solution {
public:
int totalNumber=0;
bool isValid(vector<int> layout, int recur)
{
for (int i=0; i<recur; ++i)
{
if (layout[i]==layout[recur]||layout[i]-layout[recur]==i-recur||layout[i]-layout[recur]==recur-i)
return false;
}
return true;
}
void helper(vector<int> layout,int recur, int n)
{
if (recur==n) totalNumber++;
else
{
for (int i=0; i<n; ++i)
{
layout[recur]=i;
if (isValid(layout,recur)) helper(layout,recur+1,n);
}
}
}
int totalNQueens(int n) {
vector<int> layout(n,-1);
helper(layout,0,n);
return totalNumber;
}
};
REMARK:
1. Easy version of the original problem N-Queens. Refer to the original problem.