1. 程式人生 > >BZOJ 4809: 皇後 搜索

BZOJ 4809: 皇後 搜索

IE 小菜 n皇後問題 isp TE LG mes IV sample

4809: 皇後

Description

眾所不知,rly現在不會玩國際象棋。但是,作為一個OIer,rly當然做過八皇後問題。這裏再啰嗦幾句,皇後可以攻擊到同行同列同對角線,在n*n的方格中擺n個皇後使其互不攻擊到,求不同的解的數量,這就是經典的n皇後問題。現在問題推廣到n皇後問題,這個問題對於你而言實在是小菜一疊。但因為上一次rly把棋盤弄破了,又拿不出新的,所以rly打算難一點點,問題就是破棋盤上的n皇後問題。他想知道……(你們懂的)。 棋子都是相同的。

Input

一行,一個正整數N。 接下來N行,每行N個數,要麽為0,表示沒壞,要麽1,表示壞了。 N<=16

Output

一行,輸出不同的解的數量。

Sample Input

4
1 0 1 1
1 1 1 0
0 1 1 1
1 1 0 1

Sample Output

1

思路:

  n皇後問題, 判一下不放即可。

技術分享圖片
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int n;
bool d[300],b[300],c[300];
int sum,a[300];
int map[18
][18]; void search(int i) { for(int j=1;j<=n;j++) { if((!b[j])&&(!c[i-j+n])&&(!d[i+j])&&(!map[i][j])) { a[i]=j; b[j]=1; c[i-j+n]=1; d[i+j]=1; if(i==n) sum++;
else search(i+1); b[j]=0; c[i-j+n]=0; d[i+j]=0; } } } int main() { cin>>n; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++)scanf("%d", &map[i][j]); search(1); cout<<sum; }
View Code

BZOJ 4809: 皇後 搜索