码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[51]N-Queens

时间:2015-02-10 14:39:14      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

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:
void init(vector<string> &temp, int n)
{
    string strtemp(n,.);
    temp.insert(temp.end(),n,strtemp);
    return;
}
bool checkij(vector<string> &temp, int i, int j)
{
    for (int ii=i-1,jleft=j-1;ii>=0&&jleft>=0;ii--,jleft--)
    {
        if(temp[ii][jleft]==Q)return false;
    }
    for (int ii=i-1,jright=j+1;ii>=0&&jright<temp.size();ii--,jright++)
    {
        if(temp[ii][jright]==Q)return false;
    }
    for (int k=0;k<temp.size();k++)
    {
        if (k!=j&&temp[i][k]==Q)return false;
        if (k!=i&&temp[k][j]==Q)return false;
    }
    return true;
}
bool solveOne(vector<vector<string>> &res,vector<string> &temp,int n, int index)
{
    if(index==n)
    {
        res.push_back(temp);
        return true;
    }
    for (int j=0;j<n;j++)
    {
        temp[index][j]=Q;
        if (checkij(temp,index,j))
        {
            solveOne(res,temp,n,index+1);
        }
        temp[index][j]=.;    
    }
}
vector<vector<string>> solveNQueens(int n) 
{
    vector<vector<string>> res;
    vector<string> temp;
    init(temp,n);
    for(int i = 0; i < n; i++) {
        temp[0][i] = Q;
        solveOne(res, temp, n, 1);
        temp[0][i] = .;
    }
    return res;
}
};

 

leetcode[51]N-Queens

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!