-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN-Queens.cpp
More file actions
85 lines (78 loc) · 2.61 KB
/
Copy pathN-Queens.cpp
File metadata and controls
85 lines (78 loc) · 2.61 KB
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
76
77
78
79
80
81
82
83
84
85
/*
O(pow(8, 8))
*/
class Solution {
public:
bool check(int row, int col, int *p) {
for (int i = 0; i < row; i++) {
if (p[i] == col || abs(row - i) == abs(col - p[i]))
return false;
}
return true;
}
void placeQueen(int row, int n, int *p, vector<vector<string> > &res) {
if (row == n) {
vector<string> tmp(n, string(n, '.'));
for (int i = 0; i < n; i++) {
tmp[i][p[i]] = 'Q';
}
res.push_back(tmp);
return;
}
for (int i = 0; i < n; i++) {
if (check(row, i, p)) {
p[row] = i;
placeQueen(row + 1, n, p, res);
}
}
}
vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > res;
int *p = (int *) malloc(sizeof(int) * n);
placeQueen(0, n, p, res);
return res;
}
// second try, iterative way
int place(int k,vector<int>& x) //判断是否符合要求;
{
int j;
for (j = 0; j < k; j++) {
if ((abs(k - j) == abs(x[j] - x[k])) || (x[j] == x[k]))
return 0;
}
return 1;
}
vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > result;
vector<int> x(n,-1);
int i, k;
x[0] = -1;
k = 0;
while (k >= 0) {
x[k] += 1;
while ((x[k] < n) && !(place(k,x)))
x[k] += 1;
if (x[k] < n) {
if (k == n- 1)
{
// count++; //k=N-1 表示也可构成一个排法;
vector<string> tmp(n,string(n,'.'));
for(int j=0;j<n;j++)
tmp[j][x[j]]='Q';
result.push_back(tmp);
}
else {
k++;
}
} else {
x[k] = -1; //when go back, recover the enviroment
k--;
}
}
return result;
}
};