轉自:http://www.cnblogs.com/chuanlong/archive/2013/04/21/3033471.html
Problem Description
在N*N的方格棋盤放置了N個皇后,使得它們不相互攻擊(即任意2個皇后不允許處在同一排,同一列,也不允許處在與棋盤邊框成45角的斜線上。
你的任務是,對於給定的N,求出有多少種合法的放置方法。 |
Input
共有若干行,每行一個正整數N≤10,表示棋盤和皇后的數量;如果N=0,表示結束。
|
Output
共有若干行,每行一個正整數,表示對應輸入行的皇后的不同放置數量。 |
Sample Input
1
8
5
0
|
Sample Output
1
92
10
|
方法一:遞歸 容易理解,但效率低點,也能Accepted
<span style="font-size:14px;">#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int q[11]; //q[1] means the coordinate of queue is (1, q[1])
int result[11];//to save the time, so record the previous time
int n;
int check(int k) //check if the kth queen is conflict with previous ones
{
int i;
i = 1;
while (i < k)
{
//k - i == abs(q[k] - q[i]) means the current queen is not 45° with other queens
if (q[i] == q[k] || k - i == abs(q[k] - q[i]))
return 0;
i++;
}
return 1;
}
int count; //record the count of rank
int flag;
void DFS(int step)
{
int i, j, k;
if (step == n + 1)
count++; <span style="color:#3333ff;"> //需要打印具體的放置方式時,可以在這裏打印,q[i]表示第i個皇后放在第i行第q[i]列</span>
else
{
for (i = 1; i <= n; i++)
{
q[step] = i;
if (check(step) == 0)
continue;
DFS(step + 1);
}
}
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
//memset();
count = 0;
if (result[n] == 0)
{
DFS(1);
result[n] = count;
}
printf("%d\n", result[n]);
}
return 0;
}</span>
方法二:運行效率更快,但不好理解
<span style="font-size:14px;">#include <stdio.h>
#include <math.h>
int q[11]; //q[1] means the coordinate of queue is (1, q[1])
int result[11];//to save the time, so record the previous time
int check(int k) //check if the kth queen is conflict with previous ones
{
int i;
i = 1;
while (i < k)
{
//k - i == abs(q[k] - q[i]) means the current queen is not 45° with other queens
if (q[i] == q[k] || k - i == abs(q[k] - q[i]))
return 0;
i++;
}
return 1;
}
//begin with the first queen, find the position for first queen
//and use DFS to go on to find next queen's position, if u can't find it, u can go back to change the previous queen's position
//untill there is no position for the fist queue to change
int Nqueens(int n)
{
int count, i, j, k;
count = 0; //record the count of rank
//begin with first queen and the zero position
k = 1;
q[k] = 0;
while (k > 0)
{
q[k]++;
//when q[k] <= n, u can go on to find q[k] satisfied the condition
while (q[k] <= n && check(k) == 0)
q[k]++;
//if q[k] <= n, which means u can find position for current queen
if (q[k] <= n)
{
//means u find the last queen, so u can record the counr
if (k == n)
count++;
//if it's not the last queen, u should go on to find the place of next queen
//and for next queen, u should begin with zero.
else
{
k++;
q[k] = 0;
}
}
else
//if u can't find the position for current queen, u should go back to modify the previous queen's position
k--;
}
return count;
}
int main()
{
int n;
while (scanf("%d", &n) != EOF && n)
{
if (result[n] == 0)
result[n] = Nqueens(n);
printf("%d\n", result[n]);
}
return 0;
}</span>