description:

八皇后
Note:

Example:

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

answer:


class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<string> queens(n, string(n, '.')); //string(int n,char c);  //用n个字符c初始化
        helper(0, queens, res);
        return res;
    }
    void helper(int curRow, vector<string>& queens, vector<vector<string>>& res) {
        int n = queens.size();
        if (curRow == n) { //如果已经进行到最后一行,就证明之前都可以,那就结束了,得到了一种可能的结果
            res.push_back(queens);
            return;
        }
        for (int i = 0; i < n; ++i) {
            if (isValid(queens, curRow, i)) {
                 // 在现在进行到的这一行,先假设放到现在这一行,看看如果和之前不冲突就继续递归
                queens[curRow][i] = 'Q'; 
                helper(curRow + 1, queens, res);
                queens[curRow][i] = '.';
                //递归之后发现不太行之后再重新把这个位置设置成'.',然后换一列继续递归
            }
        }
    }
    bool isValid(vector<string>& queens, int row, int col) { //因为之前是就在这一行看,找一列合格的,所以不用检查行了,这一行一定就它一个皇后
        for (int i = 0; i < row; ++i) {
            if (queens[i][col] == 'Q') return false;
        }
        for (int i = row - 1, j = col + 1; i >= 0 && j < queens.size(); --i, ++j) {
            if (queens[i][j] == 'Q') return false;
        }
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
            if (queens[i][j] == 'Q') return false;
        }
        return true;
    }
};

relative point get√:

  • string(int n,char c); //用n个字符c初始化

hint :