N后问题回溯

#include"iostream"
#include"vector"
#include"string"
using namespace std;
//由于在x,y坐标上放入皇后,8个方向都不能有其他皇后,所以将这8个方向对应的坐标置1
void put_down_the_queen(int x,int y,vector<vector<int> > &mark)
{
    static const int dx[]={-1,1,0,0,-1,1,1,-1};
    static const int dy[]={0,0,-1,1,1,1,-1,-1};
    mark[x][y] = 1;
    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_y>=0&&new_x<mark.size()&&new_y<mark.size())
            mark[new_x][new_y] = 1;
    }
}
//k表示行,n表示列,location作为放置皇后Q的棋盘,mark作为放入皇后后的坐标(1表示不能放,0可以)
//result作为保存最后的生成结果
void generate(int k,int n,
              vector<string>  &location,
              vector<vector<string> > &result,
              vector<vector<int> > &mark)
{
    if(k==n){
        result.push_back(location);
        return;
    }
    for(int i=0;i<n;i++){
        if(mark[k][i]==0){
            vector<vector<int> > temp_mark = mark;
            location[k][i] = 'Q';
            put_down_the_queen(k,i,mark);
            generate(k+1,n,location,result,mark);
            mark = temp_mark;
            location[k][i] = '.';
        }
    }



}
int main()
{
    int n;
    cin>>n;
    vector<vector<string> >   result;
    vector<string>   location;
    vector<vector<int> >    mark(n,vector<int>(n,0));
    for(int i=0;i<n;i++)
    {
        location.push_back("");
        location[i].append(n,'.');
    }
    generate(0,n,location,result,mark);
    for(int i=0;i<result.size();i++)
    {
        for(int j=0;j<n;j++)
    {
        cout<<result[i][j];
        cout<<endl;
    }
    cout<<endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1egenda

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值