-
Notifications
You must be signed in to change notification settings - Fork 1
/
52.cpp
executable file
·78 lines (77 loc) · 2.42 KB
/
52.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
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> find;
vector<vector<string> > answer;
int nu;
void dfs(int now){
if (now == nu+1){
vector<string> answertmp = find;
for (int i = 0; i < nu;i++)
for (int j = 0; j < nu; j++)
if (answertmp[i][j] == 'X')
answertmp[i][j] = '.';
for (int i = 0; i < answer.size(); i++){
bool same = true;
for (int j = 0; j < answer[i].size(); j++){
if (answer[i][j] != answertmp[j]){
same = false;
break;
}
}
if (same) return;
}
answer.push_back(answertmp);
return;
}
int i = now-1;
for (int j = 0; j < nu; j++)
if (find[i][j] != 'X'){
vector<string> tmpforfind = find;
find[i][j] = 'Q';
for (int k = 0; k < nu; k++){
if (k != j)
find[i][k] = 'X';
if (k != i)
find[k][j] = 'X';
}
int nowx = i; int nowy = j;
while (nowx - 1 >= 0 && nowy - 1 >= 0){
find[nowx - 1][nowy - 1] = 'X';
nowx --; nowy --;
}
nowx = i; nowy = j;
while (nowx + 1 < nu && nowy + 1 < nu){
find[nowx + 1][nowy + 1] = 'X';
nowx ++; nowy ++;
}
nowx = i; nowy = j;
while (nowx + 1 < nu && nowy - 1 >= 0){
find[nowx + 1][nowy - 1] = 'X';
nowx ++; nowy --;
}
nowx = i; nowy = j;
while (nowx - 1 >= 0 && nowy + 1 < nu){
find[nowx - 1][nowy + 1] = 'X';
nowx --; nowy ++;
}
dfs(now+1);
find = tmpforfind;
}
}
int totalNQueens(int n) {
nu = n;
vector<string> tmp;
for (int i = 0; i < n;i++){
string tmpstr = "";
for (int j = 0; j < n; j++)
tmpstr += ".";
tmp.push_back(tmpstr);
}
find = tmp;
dfs(1);
return answer.size();
}
};