-
Notifications
You must be signed in to change notification settings - Fork 2
/
52.cpp
140 lines (123 loc) · 3.26 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Author : Accagain
// Date : 17/3/28
// Email : chenmaosen0@gmail.com
/***************************************************************************************
*
* Follow up for N-Queens problem.
*
* Now, instead outputting board configurations, return the total number of distinct solutions.
*
* 做法:
* dfs
* 时间复杂度:
*
*
****************************************************************************************/
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#define INF 0x3fffffff
using namespace std;
class Solution {
public:
int hav[110][110];
string char2str(char c)
{
stringstream tmp;
string res;
tmp << c;
res = tmp.str();
return res;
}
void dfs(vector<vector<char>> & now, vector<vector<string> > & ans, int pos)
{
if(pos == now.size())
{
vector<string> tmp;
for(int i=0; i<now.size(); i++)
{
string get = "";
for(int j=0; j<now[i].size(); j++)
{
get += char2str(now[i][j]);
}
tmp.push_back(get);
//printf("%s\n", get.c_str());
}
ans.push_back(tmp);
return ;
}
for(int j=0; j<now.size(); j++)
{
int i = pos;
if(hav[0][i])
continue;
{
/*
* 0表示行
* 1表示列
* 2~2n+1表示上斜
* 2n+2~4n表示下斜
*/
if(hav[1][j])
continue;
int n = now.size();
int up_x = n - 1 - i + j;
int down_x = i + j;
if(!hav[2][up_x] && !hav[3][down_x])
{
now[i][j] = 'Q';
hav[0][i] = 1;
hav[1][j] = 1;
hav[2][up_x] = 1;
hav[3][down_x] = 1;
dfs(now, ans, pos+1);
now[i][j] = '.';
hav[0][i] = 0;
hav[1][j] = 0;
hav[2][up_x] = 0;
hav[3][down_x] = 0;
}
}
}
}
int totalNQueens(int n){
int hav[4][2*n]; // 分别表示行、列、上斜、下斜,1/1/2n-1/2n-1
memset(hav, 0, sizeof(hav));
vector<vector<string>> ans;
vector<vector<char>> now;
for(int i=0; i<n; i++)
{
vector<char> tmp;
for(int j=0; j<n ;j++)
tmp.push_back('.');
now.push_back(tmp);
}
dfs(now, ans, 0);
return ans.size();
}
};
int main() {
Solution *test = new Solution();
int data[] = {};
vector<int> x(data, data + sizeof(data) / sizeof(data[0]));
vector<vector<string>> ans;
int a = test->totalNQueens(4);
/*
for(int i=0; i<ans.size(); i++)
{
printf("i: %d\n", i);
for(int j=0; j<ans[i].size(); j++)
{
printf("%s\n", ans[i][j].c_str());
}
}*/
printf("%d\n", a);
return 0;
}
//
// Created by cms on 17/3/28.
//