n皇后问题

N皇后问题

  • 通过递归回溯来实现n皇后的摆放位置,下面是自己实现的代码,思路写在代码注释里,可以详细看看代码。
class Solution {
public:
    //标记mark数组
    void remark(int x,int y,vector<vector<int>> &mark)
    {
        if(x >= mark.size() || y >= mark.size())
        {
            return;
        }
        mark[x][y] = 1;
        //用mark记录当前行皇后的攻击位置
        //每次循环往八个方向延伸一次,标记攻击位置
        for(int i = 1;i < mark.size();i++)
        {
            for(int j = 0;j < 8;j++)	//八个方向
            {
                int new_x = x + i*dx[j];
                int new_y = y + i*dy[j];
                if(new_x >= 0 && new_x < mark.size() && new_y >= 0 && new_y < mark.size())
                {
                    mark[new_x][new_y] = 1;
                }
            }
        }
    }
    void generate(int k,int n,		//k:当前行。n:n*n矩阵
            vector<string> &location,
            vector<vector<string>> &result,
            vector<vector<int>> &mark)
        {
            //放完最后一个皇后的时候返回
            if(k == n)
            {
                result.push_back(location);
                return;
            }
            //每n个皇后一个循环(n*n矩阵)
            for(size_t i = 0;i < n;i++)
            {
                //当该位置不被标记时才能放置皇后,否则为前几行皇后的攻击路线
                if(mark[k][i] != 1)
                {
                    //1.放置皇后,并标记mark矩阵
                    location[k].replace(i,1,"Q");
                    vector<vector<int>> tmp_mark = mark;
                    remark(k,i,mark);
                    //2.递归放置下一行皇后
                    generate(k+1,n,location,result,mark);
                    //3.回溯,返回当前状态
                    location[k].replace(i,1,".");
                    mark = tmp_mark;
                }

            }
        }
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> result;//结果
        vector<vector<int>> mark;   //记录皇后的攻击位置
        vector<string> location;    //记录皇后的摆放位置
        //mark、location矩阵初始化
        for(int i = 0;i < n;i++)
        {
            mark.push_back(vector<int> (n,0));
            location.push_back(string (n,'.'));
        }
        //递归搜索位置
        generate(0,n,location,result,mark);
        return result;
    }
private:
    //方向数组,用以表示皇后的攻击路线
    const int dx[8] = {-1,1,0,0,-1,-1,1,1};
    const int dy[8] = {0,0,-1,1,-1,1,-1,1};
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值