【DP合集】棋盘 chess

给出一张 n × n 的棋盘,格子有黑有白。现在要在棋盘上放棋子,要求: 
• 黑格子上不能有棋子 
• 每行每列至多只有一枚棋子 
你的任务是求出有多少种合法的摆放方案。答案模 109+7109+7 。

Input

输入的第一行一个整数 n ( n ≤ 15) 。 
接下来一个 n × n 的棋盘( 1 表示黑 ;0 表示白)。

Output

输出一行一个整数,表示合法方案数对 109+7109+7 取模后的结果。

题解:
其实这道题可能是由炮兵阵地改的,但没原题好,反正记忆化搜索就可以了。
代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<cstring>
using namespace std;
const int mod=1000000007;
string a[20];
int dp[20][1<<15],vis[20][1<<15],n;
 
void cl(){
    memset(dp,0,sizeof(dp));
    memset(vis,0,sizeof(vis));
}
 
int dfs(int now,int x){
    if(now==n) return 1;
    if(vis[now][x]) return dp[now][x];
    vis[now][x]=1;
    int ans=0;
    for(int i=0;i<n;i++){
        if((1<<i)&x || a[now][i]=='1') continue;
        ans+=dfs(now+1,x|(1<<i));
        ans%=mod;
    }
    ans+=dfs(now+1,x);
    ans%=mod;
    dp[now][x]=ans;
    return ans;
}
 
int main(){
    cl();
    scanf("%d",&n);
    for(int i=0;i<n;i++)cin>>a[i];
    printf("%d",dfs(0,0));
}
原文地址:https://www.cnblogs.com/renjianshige/p/7192479.html