[leetcode] 51. N-Queens

题目:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

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.

代码:

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<int> site(n);
        deal(res, n, 0, site);
        return res;
    }
    
    void deal(vector<vector<string> >& res, int n, int row, vector<int> site){
        if(row == n){
            vector<string> item;
            for(int i = 0; i < n; i++){
                string temp = "";
                for(int j = 0; j < n; j++){
                    if(site[i] == j) temp += 'Q';
                    else temp += '.';
                }
                item.push_back(temp);
            }
            res.push_back(item);
            return;
        }
        
        for(int j = 0; j < n; j++){
            if(isValid(site, row, j)){
                site[row] = j;
                deal(res, n, row+1, site);
            }
        }
    }
    
    bool isValid(vector<int> site, int row, int j){
        for(int i = 0; i < row; i++){
            if(site[i] == j || abs(j - site[i]) == abs(row - i)) return false;
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/jing16337305/article/details/80771355