Monday, January 26, 2015

51 N-Queens

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.."]
]
class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string>> strRes;
        if (n<=0)
            return strRes;
        vector<int> res = vector<int>(n,0);
        help(n,res,0,strRes);
        return strRes;
    }
    void help(int n,vector<int>& res,int i,vector<vector<string>> &strRes)
    {
        if (i>=n)
            return store(res,strRes);
        for (int j=0;j<n;j++)
        {
            if (isValid(res,i,j))
            {
                res[i]=j;
                help(n,res,i+1,strRes);
                res[i]=0;
            }
        }
    }
    bool isValid(vector<int>& res,int i,int j)
    {
        for (int k=0;k<i;k++)
        {
            if (res[k]==j || abs(res[k]-j)==(i-k))
                return false;
        }
        return true;
    }
    void store(vector<int>& res,vector<vector<string>>& strRes)
    {
        int n = res.size();
        string level(n,'.');
        vector<string> emptyMatrix = vector<string>(n,level);
        for (int i=0;i<n;i++)
        {
            emptyMatrix[i][res[i]]='Q';
        }
        strRes.push_back(emptyMatrix);
    }
    
};

No comments:

Post a Comment