/**/
/*
* 文件名:m.cpp
* 功能:实现 N 皇后
* 创建日期:2007-10-17
*/
#include < iostream >
using namespace std;
bool place( int x[], int k)
... {
int i;
for(i = 0; i < k; i++)
...{
if(x[i] == x[k] || abs(i-k) == abs(x[i]-x[k]))
return false;
}
return true;
}
void Queen( int x[], int n)
... {
int k = 0;
x[k] = -1;
while(k >= 0)
...{
++x[k];
while((x[k] < n) && (!place(x, k)))
++x[k];
if(x[k] < n)
...{
if(k == n-1)
break;
else
...{
++k;
x[k] = -1;
}
}
else
...{
x[k] = -1;
--k;
}
}
}
int main()
... {
int i, j, n;
int *X = NULL;
cout << "please input n:";
cin >> n;
X = new int[n];
Queen(X, n);
for(i = 0; i < n; i++)
cout << X[i] << " ";
cout << endl << endl;
for(i = 0; i < n; i++)
...{
for(j = 0; j < n; j++)
...{
if(X[i] == j)
cout << "o ";
else
cout << "* ";
}
cout << endl;
}
cout << endl;
delete []X;
X = NULL;
return 0;
}
* 文件名:m.cpp
* 功能:实现 N 皇后
* 创建日期:2007-10-17
*/
#include < iostream >
using namespace std;
bool place( int x[], int k)
... {
int i;
for(i = 0; i < k; i++)
...{
if(x[i] == x[k] || abs(i-k) == abs(x[i]-x[k]))
return false;
}
return true;
}
void Queen( int x[], int n)
... {
int k = 0;
x[k] = -1;
while(k >= 0)
...{
++x[k];
while((x[k] < n) && (!place(x, k)))
++x[k];
if(x[k] < n)
...{
if(k == n-1)
break;
else
...{
++k;
x[k] = -1;
}
}
else
...{
x[k] = -1;
--k;
}
}
}
int main()
... {
int i, j, n;
int *X = NULL;
cout << "please input n:";
cin >> n;
X = new int[n];
Queen(X, n);
for(i = 0; i < n; i++)
cout << X[i] << " ";
cout << endl << endl;
for(i = 0; i < n; i++)
...{
for(j = 0; j < n; j++)
...{
if(X[i] == j)
cout << "o ";
else
cout << "* ";
}
cout << endl;
}
cout << endl;
delete []X;
X = NULL;
return 0;
}