回溯法 剪枝 八皇后问题

来源:互联网 发布:什么事软件硬件接口 编辑:程序博客网 时间:2024/06/05 22:35
#include<iostream>#include<cstring>#include<cstdio>using namespace std;const int maxn = 8;const int maxt = 100;char idx[maxt][maxt];int A[maxt], B[maxt], C[maxt] ; // 列,正对角线,反对角线void dfs(int deep)//deep代表行{    if(deep > maxn-1) //满足条件输出棋盘    {        for(int i = 0; i < maxn; i++)        {            for(int j = 0; j < maxn; j++)                cout << idx[i][j];            cout << endl;        }        cout << endl;        return;    }    for(int j = 0; j < maxn; j++)    {//        cout << j << endl;        if(!A[j] && !B[j-deep] && !C[j+deep])        {//            cout << deep << "," << j << endl;            A[j] = B[j-deep] = C[j+deep] = 1;            idx[deep][j] = '@';            dfs(deep+1);            A[j] = B[j-deep] = C[j+deep] = 0;            idx[deep][j] = '#';        }    }}int main (){    memset(A, 0, sizeof(A));    memset(B, 0, sizeof(B));    memset(C, 0, sizeof(C));    for(int i = 0; i < maxt; i++)        for(int j = 0; j < maxt; j++)            idx[i][j] = '#';    dfs(0);    return 0;}
原创粉丝点击