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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

一道深度搜索题目,用三个数组表示主对角线,副对角线,列,有没有queen占据,用此信息剪枝

Have you been asked this question in an interview? 
class Solution {
public:
    void dfs(vector<vector<string> >&result,vector<int> path,vector<int> diag1,vector<int> diag2,vector<int> col,int n){
        if(path.size()==n){
            vector<string> ans;
            for(int i=0;i<n;i++){
                string temp(n,'.');
                temp[path[i]]='Q';
                ans.push_back(temp);
            }
            result.push_back(ans);
            return;
        }
        for(int i=0;i<n;i++){
            if(col[i]==0&&diag1[path.size()+i]==0&&diag2[path.size()+n-1-i]==0){
                col[i]=diag1[path.size()+i]=diag2[path.size()+n-1-i]=1;
                path.push_back(i);
                dfs(result,path,diag1,diag2,col,n);
                path.pop_back();
                col[i]=diag1[path.size()+i]=diag2[path.size()+n-1-i]=0;
            }
        }
    }
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > result;
        vector<int> path;
        vector<int> diag1(2*n-1,0);
        vector<int> diag2(2*n-1,0);
        vector<int> col(n,0);
        dfs(result,path,diag1,diag2,col,n);
        return result;
    }
};


你可能感兴趣的:(LeetCode)