题解 | #八皇后#
八皇后
http://www.nowcoder.com/practice/fbf428ecb0574236a2a0295e1fa854cb
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<algorithm>
#include<string>
#include<set>
using namespace std;
vector<long int> vec;
int mp[9][9] = { 0,0,0,0,0,0,0,0,0 };
string ans = "";
bool check(int row, int col) {
for (int i = row - 1; i >= 1; --i) {
if (mp[i][col] == 1)
return false;
}
for (int i = row - 1,j = col; i >= 1; --i) {
if (j - 1 >= 1 && mp[i][--j] == 1)
return false;
}
for (int i = row - 1, j = col; i >= 1; --i) {
if (j + 1 <= 8 && mp[i][++j] == 1)
return false;
}
return true;
}
void dfs(int row) {
if (row == 9) {
vec.push_back(atol(ans.c_str()));
return;
}
for (int col = 1; col <= 8; ++col) {
if (check(row, col)) {
mp[row][col] = 1;
ans = ans + to_string(col);
dfs(row + 1);
mp[row][col] = 0;
ans.erase(ans.end() - 1);
}
}
}
int main()
{
int b;
while (cin >> b) {
dfs(1);
sort(vec.begin(), vec.end(), [](const long int a, const long int b) {
return a < b;
});
set<long int> s(vec.begin(),vec.end());
vec.clear();
vec.assign(s.begin(), s.end());
cout << vec[b - 1] << endl;
}
}