深度优先搜索
代码:
#include <iostream>
#include <cstring>
using namespace std;
int n,k;
char array[10][10]; //to record the chessboard
bool visited[10]; //to record each line's status
int ans ;
int sum ;
void dfs(int d,int sum){ //d represent the line, sum represent the chess number in the chessboard
if(sum == k){
ans++;
return;
}
if(d == n+1)
return;
for(int j=1;j<=n;j++) // start from the dth row
if(!visited[j] && array[d][j] == '#'){
visited[j] = true;
dfs(d+1,sum+1);
visited[j] = false;
}
dfs(d+1,sum); //start from the (d+1)th row
}
int main(){
while(cin>>n>>k && (n!=-1) && (k!=-1)){
ans = 0,sum=0;
memset(visited,false,sizeof(visited));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>array[i][j];
dfs(1,0);
cout<<ans<<endl;
}
return 0;
}