回溯法 剪枝 八皇后问题

#include
#include
#include
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;
}

你可能感兴趣的:(简单搜索)