回溯法求八皇后

#include <QCoreApplication>
#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <stdio.h>

using namespace std;

#define N 8

int row[N];	//四个方向
int col[N];
int dpos[2*N-1];
int dneg[2*N-1];
int Map[N][N];

int ord = 0;

void PP(void)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            cout << Map[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
}

void Res(int x)
{
    if(x == N)
    {
        PP();
        return;
    }

    for(int y = 0; y < N; y++)
    {
    	//只有当四个方向都没有被攻击时才能放置
        if(row[x] == 0 && col[y] == 0 && dpos[x+y] == 0 && dneg[x-y+N-1] == 0)
        {
            Map[x][y] = ++ord;
            row[x] = col[y] = dpos[x+y] = dneg[x-y+N-1] = 1;

            Res(x+1);
			
			
            row[x] = col[y] = dpos[x+y] = dneg[x-y+N-1] = 0;    //放置失败,取消该行的皇后
            Map[x][y] = 0;
            ord--;
        }
    }

}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    freopen("G:\\data.txt", "r", stdin);


    Res(0);


    return a.exec();
}
















猜你喜欢

转载自blog.csdn.net/canhelove/article/details/88410852