8皇后测试

#include <iostream>
#include <math.h>
#include <list>
using namespace std;
const int count = 8;
char pos[count] = {0};
int kinds = 0;
list<char *> l;
bool check_pos(int index) //1到count
{
    for(int i = 0; i < index-1; i++) //
    {
        if(pos[i] == pos[index-1]) //在一列
        {
            return false;
        }
        else if(abs(pos[i] - pos[index-1]) == abs(index - i-1))//正斜线
        {
            return false;
        }
    }
    return true;
}
void queen(int index) //index从1开始 第几个皇后 ,当前的坐标
{
    if(index > count)
    {
        char*a = new char[count];
        memcpy(a,pos,count);
        l.push_back(a);
        kinds++;
        return;
    }
    for(int i = 1; i <= count; i++) //
    {
        pos[index-1] = i; //循环设置自己坐标
        if(index == 1)
        {
            queen(index+1);
        }
        else
        {
            bool flag = false;
            flag = check_pos(index); //与已经有的皇后坐标判断
            if(flag) //找到皇后位置,再找下一个皇后
            {
                queen(index+1);
            }
        }
    }
}


int main()
{
    cout << "Hello World!" << endl;
    queen(1);
    cout << "find " << l.size() << endl;
    list<char*>::iterator it = l.begin();
    int n = 0;
    while(it != l.end())
    {
        cout << "method " << ++n << " :" << endl;
        char *a = *it;
        for(int m = 0; m < count; m++)
        {
//            cout << (int)a[m] << " ";
            cout << a[m] << " ";

        }
        cout << endl;

        for(int i = 0; i < count; i++)
        {
            for(int j = 1; j <= count; j++)
            {
                if(a[i] == j)
                {
                    cout << " Q";
                }
                else
                {
                    cout << " *";
                }
            }
            cout << endl;
        }
        it++;
        delete []a;
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值