| 
 | 1 | + | 
 | 2 | +# 题目链接   | 
 | 3 | + | 
 | 4 | +https://leetcode-cn.com/problems/n-queens/   | 
 | 5 | + | 
 | 6 | +# 第51题. N皇后  | 
 | 7 | +n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。   | 
 | 8 | + | 
 | 9 | +上图为 8 皇后问题的一种解法。  | 
 | 10 | +  | 
 | 11 | + | 
 | 12 | +给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。  | 
 | 13 | + | 
 | 14 | +每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。  | 
 | 15 | + | 
 | 16 | +示例:  | 
 | 17 | + | 
 | 18 | +输入: 4  | 
 | 19 | +输出: [  | 
 | 20 | + [".Q..", // 解法 1  | 
 | 21 | + "...Q",  | 
 | 22 | + "Q...",  | 
 | 23 | + "..Q."],  | 
 | 24 | + | 
 | 25 | + ["..Q.", // 解法 2  | 
 | 26 | + "Q...",  | 
 | 27 | + "...Q",  | 
 | 28 | + ".Q.."]  | 
 | 29 | +]  | 
 | 30 | +解释: 4 皇后问题存在两个不同的解法。  | 
 | 31 | + | 
 | 32 | +提示:  | 
 | 33 | + | 
 | 34 | +> 皇后,是国际象棋中的棋子,意味着国王的妻子。皇后只做一件事,那就是“吃子”。当她遇见可以吃的棋子时,就迅速冲上去吃掉棋子。当然,她横、竖、斜都可走一到七步,可进可退。(引用自 百度百科 - 皇后 )  | 
 | 35 | +
  | 
 | 36 | + | 
 | 37 | +# 思路  | 
 | 38 | + | 
 | 39 | +# C++代码  | 
 | 40 | + | 
 | 41 | +```  | 
 | 42 | +class Solution {  | 
 | 43 | +private:  | 
 | 44 | +void backtracking(int n, int row, vector<string>& chessboard, vector<vector<string>>& result) {  | 
 | 45 | + if (row == n) {  | 
 | 46 | + result.push_back(chessboard);  | 
 | 47 | + return;  | 
 | 48 | + }  | 
 | 49 | + for (int col = 0; col < n; col++) {  | 
 | 50 | + if (isValid(row, col, chessboard, n)) {  | 
 | 51 | + chessboard[row][col] = 'Q';  | 
 | 52 | + backtracking(n, row + 1, chessboard, result);  | 
 | 53 | + chessboard[row][col] = '.';  | 
 | 54 | + }  | 
 | 55 | + }  | 
 | 56 | +}  | 
 | 57 | +bool isValid(int row, int col, vector<string>& chessboard, int n) {  | 
 | 58 | + int count = 0;  | 
 | 59 | + // 检查列  | 
 | 60 | + for (int i = 0; i < row; i++) { // 这是一个剪枝  | 
 | 61 | + if (chessboard[i][col] == 'Q') {  | 
 | 62 | + return false;  | 
 | 63 | + }  | 
 | 64 | + }  | 
 | 65 | + // 检查 45度角是否有皇后  | 
 | 66 | + for (int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--) {  | 
 | 67 | + if (chessboard[i][j] == 'Q') {  | 
 | 68 | + return false;  | 
 | 69 | + }  | 
 | 70 | + }  | 
 | 71 | + // 检查 135度角是否有皇后  | 
 | 72 | + for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {  | 
 | 73 | + if (chessboard[i][j] == 'Q') {  | 
 | 74 | + return false;  | 
 | 75 | + }  | 
 | 76 | + }  | 
 | 77 | + return true;  | 
 | 78 | +}  | 
 | 79 | +public:  | 
 | 80 | + vector<vector<string>> solveNQueens(int n) {  | 
 | 81 | + std::vector<std::string> chessboard(n, std::string(n, '.'));  | 
 | 82 | + vector<vector<string>> result;  | 
 | 83 | +
  | 
 | 84 | + backtracking(n, 0, chessboard, result);  | 
 | 85 | + return result;  | 
 | 86 | + }  | 
 | 87 | +};  | 
 | 88 | +```  | 
0 commit comments