HDU-2553
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
my analysis
If the direct point by point DFS enumeration, can only be solved in the limited time, while n belongs to the range of 1 to 9, can not solve N = 10, refer to method one.After improvement, line by line DFS, can solve the situation when n = 10, need to pay attention to, no matter which method, need to “hit the table”.
solution one
#include<iostream>
#include<map>
using namespace std;
int N, sum = 0;
bool judgeX[10000] = { false };
bool judgeY[10000] = { false };
map<int, bool> judgeL;
bool judgeR[10000] = { false };
bool judge(int x, int y, int l, int r)
{
if (judgeX[x] || judgeY[y] || judgeL[l] || judgeR[r])
return false;
else
return true;
}
void DFS(int index, int nowN)
{
if (nowN == N)
{
sum++;
return;
}
if (index >= N * N)
return;
int x = index / N;
int y = index % N;
int l = x - y;
int r = x + y;
if (x > 0)
if (N < x)
return;
if (judge(x, y, l, r))
{
judgeX[x] = true;
judgeY[y] = true;
judgeL[l] = true;
judgeR[r] = true;
DFS(index + N - y, nowN + 1);
judgeX[x] = false;
judgeY[y] = false;
judgeL[l] = false;
judgeR[r] = false;
}
DFS(index+1, nowN);
}
int main()
{
long long int res[11];
for (int i = 1; i < 10; i++)
{
sum = 0;
N = i;
memset(judgeX, false, sizeof(judgeX));
memset(judgeY, false, sizeof(judgeY));
judgeL.clear();
memset(judgeR, false, sizeof(judgeR));
DFS(0, 0);
res[i] = sum;
}
res[10] = 724;
while (cin >> N && N != 0)
cout << res[N] << endl;
}
solution two
#include<iostream>
#include<map>
using namespace std;
int N, sum = 0;
bool judgeX[10000] = { false };
bool judgeY[10000] = { false };
map<int, bool> judgeL;
bool judgeR[10000] = { false };
bool judge(int x, int y, int l, int r)
{
if (judgeX[x] || judgeY[y] || judgeL[l] || judgeR[r])
return false;
else
return true;
}
void DFS(int nowR)
{
if (nowR == N)
{
sum++;
return;
}
for (int j = 0; j < N; j++)
{
int l = nowR - j;
int r = nowR + j;
if (judge(nowR, j, l, r))
{
judgeX[nowR] = true;
judgeY[j] = true;
judgeL[l] = true;
judgeR[r] = true;
DFS(nowR + 1);
judgeX[nowR] = false;
judgeY[j] = false;
judgeL[l] = false;
judgeR[r] = false;
}
}
}
int main()
{
long long int res[11];
for (int i = 1; i < 11; i++)
{
sum = 0;
N = i;
memset(judgeX, false, sizeof(judgeX));
memset(judgeY, false, sizeof(judgeY));
judgeL.clear();
memset(judgeR, false, sizeof(judgeR));
DFS(0);
res[i] = sum;
}
while (cin >> N && N != 0)
cout << res[N] << endl;
}