-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn-queens-ii.cpp
111 lines (87 loc) · 2.48 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class Solution {
public:
vector<bool> shun,ni,lie;
int res;
int totalNQueens(int n) {
res=0;
shun.resize(2*n,true);
ni.resize(2*n,true);
lie.resize(n,true);
dfs(0,n);
return res;
}
void dfs(int row, int n){
if(row==n){
res++;
return;
};
for(int col=0;col<n;col++){
int id1=row+col;
int id2=row-col+n;
if(!(shun[id1] && ni[id2] && lie[col])) continue;
shun[id1]=ni[id2]=lie[col]=false;
dfs(row+1,n);
shun[id1]=ni[id2]=lie[col]=true;
}
}
/*
//二刷了,还是要看题解。
vector<bool> shun;
vector<bool> ni;
vector<bool> lie;
int res;
int totalNQueens(int n) {
shun.resize(n+n,true);
ni.resize(n+n,true);
lie.resize(n,true);
helper(0,n);
return res;
}
void helper(int row, int n){
if(row==n){
res++;
return ;
}
for(int col=0;col<n;col++){
int id1=row+col;
int id2=row-col+n;
if(!(shun[id1] && ni[id2] && lie[col])) continue;
shun[id1]=ni[id2]=lie[col]=false;
helper(row+1,n);
shun[id1]=ni[id2]=lie[col]=true;
}
}
*/
/*
(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3)
(3,0) (3,1) (3,2) (3,3)
这么 / 是x+y 的值相等
这么 \ 是x-y 的值相等
*/
//比这道题目简单些https://leetcode.com/problems/n-queens/description/
//copy了这个:https://leetcode.com/problems/n-queens-ii/discuss/20048/Easiest-Java-Solution-(1ms-98.22)
int count;
int totalNQueens1(int n) {
count=0;
vector<bool> cols(n);
vector<bool> shun(n+n);
vector<bool> ni(n+n);
helper1(0,n,cols,shun,ni);
return count;
}
void helper1(int row, int n, vector<bool> &cols, vector<bool> &shun, vector<bool> &ni){
if(row==n){
count++;
}
for(int col=0;col<n;col++){ //在该行,看看这个queue可以放在哪列
int id1=row+col;
int id2=row-col+n;
if(cols[col] || shun[id1] || ni[id2]) continue;
cols[col]=shun[id1]=ni[id2]=true;
helper1(row+1,n,cols,shun,ni);
cols[col]=shun[id1]=ni[id2]=false;
}
}
};