class Solution { private: int queen_num; vector<vector<string> > res; public: vector<vector<string> > solveNQueens(int n) { res.clear(); queen_num = n; vector<bool> h(n, false); vector<bool> v(n, false); vector<bool> lx(n * 2 + 1, false); vector<bool> rx(n * 2 + 1, false); vector<int> solution; dfs(solution, h, v, lx, rx); return res; } void dfs(vector<int> &mem, vector<bool> &h, vector<bool> &v, vector<bool> &lx, vector<bool> &rx) { if (mem.size() == queen_num) { add_solution(mem); return; } int row = mem.size(); int col = 0; while (col < queen_num) { if (!h[row] && !v[col] && !lx[row + col] && !rx[row + queen_num - col - 1]) { h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = true; mem.push_back(col); dfs(mem, h, v, lx, rx); mem.pop_back(); h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = false; } col++; } } void add_solution(vector<int> &solution) { res.push_back(vector<string>()); string line(queen_num, '.'); for (int i=0; i<queen_num; i++) { line[solution[i]] = 'Q'; res.back().push_back(line); line[solution[i]] = '.'; } } };
第二轮:
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
class Solution { private: vector<vector<string> > solutions; public: vector<vector<string> > solveNQueens(int n) { vector<int> H(n, 0); vector<int> V(n, 0); vector<int> S1(n*2, 0); vector<int> S2(n*2, 0); vector<string> res; solutions.clear(); dfs(n, 0, H, V, S1, S2, res); return solutions; } void dfs(int n, int i, vector<int>& H, vector<int>& V, vector<int>& S1, vector<int>& S2, vector<string>& res) { if (i == n) { solutions.push_back(res); return; } for (int j=0; j<n; j++) { if (!H[i] && !V[j] && !S1[n-i-1 + j] && !S2[i+j]) { H[i] = V[j] = S1[n-i-1 + j] = S2[i+j] = 1; string s(n, '.'); s[j] = 'Q'; res.push_back(s); dfs(n, i + 1, H, V, S1, S2, res); res.pop_back(); H[i] = V[j] = S1[n-i-1 + j] = S2[i+j] = 0; } } } };