Thursday, April 30, 2015

[LeetCode] 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.."]
]
class Solution {
public:
    bool isOK(vector<int> &vec, int index)
    {
        int size = vec.size();
        if(0 == size) return true;
        for(int i=0;i<size;i++)
        {
            if(vec[i] == index) return false;
            if(abs(index - vec[i])==size-i) return false;
        }
        return true;
    }

    void solve(vector<vector<string>> &res, 
                 vector<int> &vec, int n)
    {
        if(vec.size() == n)
        {
            vector<string> temp(n,string(n,'.'));
            for(int i=0;i<n;i++)temp[i][vec[i]]='Q';
            res.push_back(temp);
            return;
        }
        for(int i=0; i<n;i++)
        {
            if(!isOK(vec,i)) continue;
            vec.push_back(i);
            solve(res, vec, n);
            vec.pop_back();
        }
    }
    vector<vector<string> > solveNQueens(int n) 
    {
        vector<vector<string> > res;
        vector<int> vec;
        solve(res, vec, n);
        return res;
    }
};