[LeetCode] N-Queen

N-Queens

  Total Accepted: 20010  Total Submissions: 77022 My Submissions

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:

这是一道搜索题,使用深度优先搜索就可以解决问题,关键是剪枝,也就是每一次放皇后的时候都要检查之前所放过的皇后的位置是否冲突,是否

再同一列或者是否在同一条斜线上

代码如下:

class NQueue
{
private:
    bool canPlace(vector<int>& beforeQueues,int p)
    {
        int curRow = (int)beforeQueues.size();
        for(int i=0;i<beforeQueues.size();i++)
        {
            bool flag = ((curRow-i==p-beforeQueues[i])||(curRow-i==beforeQueues[i]-p));
            if(flag||(p==beforeQueues[i]))
                return false;
        }
        return true;
    }
    void generate(vector<string>& result,vector<int> cols)
    {
        for(int i=0;i<cols.size();i++)
        {
            string tmp = "";
            for(int j=0;j<cols.size();j++)
            {
                if(j!=cols[i])
                    tmp+=".";
                else
                    tmp+="Q";
            }
            result.push_back(tmp);
        }
    }
    void _nqueue(vector<vector<string> >& ret,int row,int n,vector<int> curResult)
    {
        if(row == n)
        {
            vector<string> result;
            generate(result,curResult);
            ret.push_back(result);
        }
        else
        {
            for(int i=0;i<n;i++)
            {
                if(canPlace(curResult,i))
                {
                    vector<int> tmp = curResult;
                    tmp.push_back(i);
                    _nqueue(ret,row+1,n,tmp);
                }
            }
        }
    }
public:
    
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > ret;
        vector<int> curResult;
        _nqueue(ret,0,n,curResult);
        return ret;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值