身为一只大二狗,表示很多东西都不会,包括n皇后问题之前理解的也不是很透彻,很羞愧的写下了这篇blog= =
n皇后问题( 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
分析:n个皇后,每行放一个,同行同列同对角线都不能有两个皇后,说起思路,都知道是搜索回溯,可是要怎么搜索回溯呢?
第一步:检查是否n个皇后都已经放好,若已经放好,ans++;
第二步:若没有放好,准备放置第cur(起初cur=1)个皇后,从第一列开始检查,到第n列;
第三步:如果当前列可以放置第cur个皇后,搜索第cur+1个皇后;
第四步:如果当前列不能放置皇后的话,继续,如果第n列都不能放的话,则回溯到cur-1列;
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 13;
int nn;
int tmp;
int pos[maxn];
int ans[maxn];
bool check( int cur)
{
for( int i = 1; i < cur; i++)
if( pos[i] == pos[cur] || abs(i-cur) == abs(pos[i]-pos[cur]))
return false;
return true;
}
void dfs( int cur, int n)
{
if( cur == n+1)
tmp++;
for( int i = 1; i <= n; i++)
{
pos[cur] = i;
/*for( int j = 1; j < cur; j++)
{
if( pos[j] == pos[cur] && abs(j-cur) == abs(pos[j]-pos[cur]))
dfs(cur+1);
}*/
if( check(cur))
dfs(cur+1,n);
}
}
int main()
{
for( int i = 1; i < maxn; i++)
{
memset(pos,0,sizeof(pos));
tmp = 0;
dfs(1,i);
ans[i] = tmp;
}
while( ~scanf("%d",&nn) && nn)
{
printf("%d\n",ans[nn]);
}
return 0;
}
2n皇后问题(wustoj-1291)
Description
给定一个n*n的棋盘,棋盘中有一些位置不能放皇后。现在要向棋盘中放入n个黑皇后和n个白皇后,使任意的两个黑皇后都不在同一行、同一列或同一条对角线上,任意的两个白皇后都不在同一行、同一列或同一条对角线上。问总共有多少种放法?n小于等于8。
Input
多组测试数据,每组数据的输入格式如下。
第一行为一个整数n,表示棋盘的大小。
接下来n行,每行n个0或1的整数,如果一个整数为1,表示对应的位置可以放皇后,如果一个整数为0,表示对应的位置不可以放皇后。
Output
输出一个整数,表示总共有多少种放法。
Sample Input
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
4
1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Sample Output
2
0
分析:这好像是某次蓝桥杯的一个题,当时以为2n皇后很复杂,其实也不,也跟n皇后差不多,但是2n皇后,要先去放好黑皇后(或白皇后),再去处理白皇后(或黑皇后),一次处理完之后ans++,具体步骤就不分析了,仔细体会~
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 10;
int n;
int mp[maxn][maxn];
int posb[maxn];
int posw[maxn];
int ans;
bool checkw( int cur)
{
for( int i = 1; i < cur; i++)
if( posw[i] == posw[cur] || abs(i-cur) == abs(posw[i]-posw[cur]))
return false;
return true;
}
bool checkb( int cur)
{
for( int i = 1; i < cur; i++)
if( posb[i] == posb[cur] || abs(i-cur) == abs(posb[i]-posb[cur]))
return false;
return true;
}
void dfs_white( int cur)
{
if( cur == n+1)
{
ans++;
/* printf("black:");
for( int i = 1; i <= n; i++)
printf("%d ",posb[i]);
putchar(10);
printf("white:");
for( int i = 1; i <= n; i++)
printf("%d ",posw[i]);
putchar(10);*/
}
for( int i = 1; i <= n; i++)
{
if( posb[cur] == i)
continue;
if( mp[cur][i] == 0)
continue;
posw[cur] = i;
if( checkw(cur))
dfs_white(cur+1);
}
}
void dfs_black( int cur)
{
if( cur == n+1)
{
dfs_white(1);
}
for( int i = 1; i <= n; i++)
{
if( mp[cur][i] == 0)
continue;
posb[cur] = i;
if( checkb(cur))
dfs_black(cur+1);
}
}
int main()
{
while( ~scanf("%d",&n) && n)
{
for( int i = 1; i <= n; i++)
for( int j = 1; j <= n; j++)
scanf("%d",&mp[i][j]);
memset(posb,0,sizeof(posb));
memset(posw,0,sizeof(posw));
ans = 0;
dfs_black( 1);
printf("%d\n",ans);
}
return 0;
}