/*回溯*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define N 20
int x[N]; //x[i]:i行的第x[i]列
int ok(int k)
{
int i;
for (i=1; i<k; i++)
{
if (x[i] == x[k] || abs(x[i]-x[k]) == abs(i-k))
return 0;
}
return 1;
}
void solve(int n)
{
int k; //找第k行上的
k = 1;
x[k] = 0;
while (k > 0)
{
x[k]++;
while (x[k] <= n && !ok(k))
{
x[k]++;
}
if (x[k] <= n)
{
if (k == n)
break;
else
{
k++;
x[k] = 0;
}
}
else
{ x[k] = 0;
k--;
}
}
}
int main()
{
int n, i;
while(scanf("%d", &n), n)
{
solve(n);
for (i=1; i<=n; i++)
{
printf("%d ",x[i]);
}
printf("\n");
}
return 0;
}
|
n最大300,此方法肯定行不通, 只能用构造法,至于构造法...网上到处都是
阅读(894) | 评论(3) | 转发(0) |