题目:
回溯:注意判断对角线时是两条对角线,方向分别为”"和”/“;
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
| #include <vector> #include <string> #include <unordered_set>
using std::vector; using std::string; using std::unordered_set;
class Solution { private: unordered_set<int> uset;
bool queen_can_stand(vector<string> &board, int n, int posi, int posj) { int i, j;
if (uset.count(posj)) return false;
i = posi; j = posj; while (i >= 0 && j >= 0) { if (board[i][j] == 'Q') return false; i--; j--; }
i = posi; j = posj; while (i < n && j < n) { if (board[i][j] == 'Q') return false; i++; j++; }
i = posi; j = posj; while (i >= 0 && j < n) { if (board[i][j] == 'Q') return false; i--; j++; }
i = posi; j = posj; while (i < n && j >= 0) { if (board[i][j] == 'Q') return false; i++; j--; }
return true; } void __solveNQueens(vector<vector<string> > &res, vector<string> &board, int n, int row) { int j;
if (row == n) { res.push_back(board); return; }
for (j = 0; j < n; j++) { if (queen_can_stand(board, n, row, j)) { uset.insert(j); board[row][j] = 'Q';
__solveNQueens(res, board, n, row + 1);
board[row][j] = '.'; uset.erase(j); } } }
public: vector<vector<string> > solveNQueens(int n) { int i; string line; vector<string> board; vector<vector<string> > res;
for (i = 0; i < n; i++) line.push_back('.');
for (i = 0; i < n; i++) board.push_back(line);
__solveNQueens(res, board, n, 0);
return res; } };
|