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
| class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string> > res; vector<string> board(n, string(n, '.')); dfs(res, board, 0); return res; } void dfs(vector<vector<string> >& res, vector<string>& board, int row) { if(row >= board.size()) { res.push_back(board); return; } int n = board[row].size(); for(int col = 0; col < n; ++col) { if(!isValid(board, row, col)) continue; board[row][col] = 'Q'; dfs(res, board, row+1); board[row][col] = '.'; } } bool isValid(vector<string>& board, int row, int col) { int n = board.size(); for(int i = 0; i < row; ++i) { if(board[i][col] == 'Q') return false; } for(int i = row-1, j = col-1; i >= 0 && j >= 0; --i, --j) { if(board[i][j] == 'Q') return false; } for(int i = row-1, j = col+1; i >= 0 && j < n; --i, ++j) { if(board[i][j] == 'Q') return false; } return true; } };
|