leave a comment »

The n-queens puzzle is the problem of placing n queens on an nn 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.",  // Solution 2
class Solution {

    vector<string> convert(vector<int> &colInd, int n){
        vector<string> result;
        int size = colInd.size();
        for(int i = 0; i < size; i++){
            string sret= "";
            for(int j = 0; j < n; j++){
                sret = sret + (j == colInd[i] ? "Q":".");
        return result;
    bool valid(vector<int> &colInd, int col){
        int done = colInd.size();
        for(int i = 0; i < done; i++){
                if(colInd[i] == col){
                    return false;
                if(abs(done - i) == abs(colInd[i] - col)){
                    return false;
        return true;
    void placeQ(vector<int> &colInd, vector<vector<string> > &ret, int total){
        int done = colInd.size();
        if(done == total){
            ret.push_back(convert(colInd, total));
            for(int j = 0; j < total; j++){
                if(valid(colInd, j)){
                    placeQ(colInd, ret, total);

    vector<vector<string> > solveNQueens(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> colInd;
        vector<vector<string> > ret; ret.clear();
        placeQ(colInd, ret, n);
        return ret;        

Written by linzhongzl

May 1, 2013 at 9:21 pm

Posted in Leetcode

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: