题解 | #八皇后#
八皇后
https://www.nowcoder.com/practice/fbf428ecb0574236a2a0295e1fa854cb
#include<iostream> #include<string> #include<algorithm> using namespace std; int n; string res[100]; int index = 0; bool isused[8][8] = { false }; bool col[8]; bool check(int x, int y) { int y1 = y; for (int i = x; i >= 0; i--) { if (y >= 0 && isused[i][y--] == true) return true; if (y1 < 8 && isused[i][y1++] == true) return true; } return false; } void DFS(int position, string str) { if (position == 8) { res[index++] = str; return; } for (int j = 0; j < 8; j++) { if (check(position, j) || col[j] == true) { //检查对角线上是否有结点 continue; } col[j] = true; isused[position][j] = true; char s = j + '0'+1; DFS(position + 1, str+s); col[j] = false; isused[position][j] = false; } } int main() { DFS(0,""); sort(res, res + 92); while (cin >> n) { cout << res[n-1]<<endl; } }