【问题描述】
一个N*N棋盘,因为棋盘太旧了,有些格子破掉不能放皇后了。
请你统计破棋盘上N皇后问题解的数量。
输入
第一行2个正整数N,K,代表棋盘大小和破格子数量
下面K行,每行2个整数,代表破格子的行、列号
输出
1个整数,代表破棋盘上N皇后问题解的数量;若无解,输出“No Solution!”
样例输入
#1:
8 4
1 1
2 2
3 3
7 5
#2:
8 0
样例输出
#1:
64
#2:
92
提示
对于100%的数据,N<=15, K<=N^2
【N皇后问题点这里】
【代码实现】
#include<iostream>
using namespace std;
const int idata=50;
bool maps[20][20]; //存放破损棋盘的位置,将其置为1
int judge[idata][3];
int n,m; //棋盘nXn;破损个数为m
int cnt; //方案总数
void dfs(int x)
{
for(int i=1;i<=n;i++)
{
if(!judge[i][0]&&!judge[i+x][1]
&&!judge[i-x+15][2]&&!maps[x][i])
{
judge[i][0]=1;
judge[i+x][1]=1;
judge[i-x+15][2]=1;
if(x==n) cnt++;
else dfs(x+1);
judge[i][0]=0; //状态恢复
judge[i+x][1]=0;
judge[i-x+15][2]=0;
}
}
}
int main()
{
int x,y;
cin>>n>>m;
while(m--)
{
cin>>x>>y;
maps[x][y]=1;
}
dfs(1);
if(cnt)
cout<<cnt<<endl;
else
cout<<"No Solution!"<<endl;
return 0;
}