通过dfs逐层搜索整个棋盘,然后枚举1-n列合法放置围棋情况和这一列没放围棋的情况,最后当cnt和k的值相同时,res自增 回溯。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char a[20][20];
bool st[20];
int res,cnt;
int n,m;
void dfs(int u)
{
if (cnt == m)
{
res ++ ;
return;
}
if (u > n) return;
for (int i=1 ;i<=n ;i++ )
{
if( a[u][i]=='#' && !st[i])
{
cnt++;
st[i]=true;
dfs(u+1);
cnt--;
st[i]=false;
}
}
dfs(u+ 1); //目的是枚举当前列不放的情况
}
int main()
{
while(1)
{
cin>>n>>m;
if(n==-1 && m==-1) break;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
{
cin>>a[i][j];
}
memset(st, 0, sizeof st);
res=cnt=0;
dfs(1);
cout << res<<endl;
}
}