TestNQueen.cpp
#include <iostream>
#include "Queen.h"
using namespace std;
int main()
{
cout << "输入皇后个数";
int n;
cin >> n;
int* M = new int[n];
int* L = new int[2 * n];
int* R = new int[2 * n];
int** A = new int*[n];
for(int i = 0; i < n; ++i)
{
A[i] = new int[n];
for(int j = 0; j < n; ++j)
{
A[i][j] = 0;
}
M[i] = 0;
}
for(int i = 0; i < 2 * n; ++i)
{
L[i] = 0;
R[i] = 0;
}
int p = mytry(0, M, L, R, A, n);
cout << "共有" << p << "种方案" << endl;
system("pause");
return 0;
}
Queen.h
#include <iostream>
using namespace std;
int qCount = 0;
void print(int** A, int n)
{
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
cout << A[i][j] << " ";
}
cout << endl;
}
cout << "------------------------------" << endl;
}
int mytry(int i, int* M, int* L, int* R, int** A, int n)
{
for(int j = 0; j < n; ++j)
{
if (!M[j] && !L[i + j] && !R[i - j + n])
{
A[i][j] = i + 1;
M[j] = L[i + j] = R[i - j + n] = 1;
if (i == n - 1)
{
print(A, n);
++qCount;
}
else
{
mytry(i + 1, M, L, R, A, n);
}
A[i][j] = 0;
M[j] = L[i + j] = R[i - j + n] = 0;
}
}
return qCount;
}