kiddy

N-Queens

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",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
class Solution {
public:


    vector<string> convert(vector<int> &colInd, int n){
        vector<string> result;
        result.clear();
        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":".");
            }
            result.push_back(sret);
        }
        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));
        }else{
            for(int j = 0; j < total; j++){
                if(valid(colInd, j)){
                    colInd.push_back(j);
                    placeQ(colInd, ret, total);
                    colInd.pop_back();
                }
            }
        }
    }


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

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s

%d bloggers like this: