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