#include<iostream>
#include<queue>
#include<cstring>
#include<string>
#include<sstream>
#include<map>
#include<vector>
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<stack>
#include<ctime>
using namespace std;
#define rep(i,aa,bb) for(register int i=aa;i<=bb;i++)
#define rrep(i,aa,bb) for(register int i=aa;i>=bb;i--)
#define LL long long
#define eps 0.000001
#define inf 0x3f3f3f3f
#define exp 0.000001
#define pai 3.141592654
#define random(x) rand()%(x)
#define lowbit(x) x&(-x)
inline int read()
{
int x = 0, y = 1; char a = getchar(); while (a > '9' || a < '0') { if (a == '-')y = -1; a = getchar(); }
while (a >= '0' && a <= '9') { x = 10 * x + a - '0'; a = getchar(); }return x * y;
}
#define N 12
int n, k;
int L=0;
int book[N]={0};
int e[N][N]; int suma = 0;
int m = 0;
void dfs(int dep){
if ( m == k ){
suma++;
return ;
}
if ( dep >= n+1 )
return;
for (int i = 1; i <= n; i++){
if ( book[i] == 0 && e[dep][i] == 0 ){
book[i] = 1;
m++;
dfs(dep+1);
m--;
book[i] = 0;
}
}
dfs(dep+1);
}
int main()
{
// freopen("1.txt", "r", stdin);
srand((int)time(0));
std::ios::sync_with_stdio(false);
while (scanf("%d%d", &n, &k) == 2) {
if ( n == -1 && k == -1) break;
L = 0;
suma = 0;m = 0;
memset(e,0,sizeof(e));
memset(book,0,sizeof(book));
rep(i,1,n) rep(j,1,n){
char c = getchar();
while ( c!='.' && c!='#') c = getchar();
if ( c == '.' )
e[i][j] = 1;
}
dfs(1);
cout<<suma<<endl;
}
return 0;
}
解法二
此解法仅为展示,次数,可以定义成全局变量或者作为参数一直走。
#include<iostream>
#include<queue>
#include<cstring>
#include<string>
#include<sstream>
#include<map>
#include<vector>
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<stack>
#include<ctime>
using namespace std;
#define rep(i,aa,bb) for(register int i=aa;i<=bb;i++)
#define rrep(i,aa,bb) for(register int i=aa;i>=bb;i--)
#define LL long long
#define eps 0.000001
#define inf 0x3f3f3f3f
#define exp 0.000001
#define pai 3.141592654
#define random(x) rand()%(x)
#define lowbit(x) x&(-x)
inline int read()
{
int x = 0, y = 1; char a = getchar(); while (a > '9' || a < '0') { if (a == '-')y = -1; a = getchar(); }
while (a >= '0' && a <= '9') { x = 10 * x + a - '0'; a = getchar(); }return x * y;
}
#define N 12
int n, k;
int L=0;
int book[N]={0};
int e[N][N]; int suma = 0;
//int m = 0;
void dfs(int dep,int m){
if ( m == k ){
suma++;
return ;
}
if ( dep >= n+1 )
return;
for (int i = 1; i <= n; i++){
if ( book[i] == 0 && e[dep][i] == 0 ){
book[i] = 1;
dfs(dep+1,m+1);
book[i] = 0;
}
}
dfs(dep+1,m);
}
int main()
{
// freopen("1.txt", "r", stdin);
srand((int)time(0));
std::ios::sync_with_stdio(false);
while (scanf("%d%d", &n, &k) == 2) {
if ( n == -1 && k == -1) break;
L = 0;
suma = 0;
// m = 0;
memset(e,0,sizeof(e));
memset(book,0,sizeof(book));
rep(i,1,n) rep(j,1,n){
char c = getchar();
while ( c!='.' && c!='#') c = getchar();
if ( c == '.' )
e[i][j] = 1;
}
dfs(1,0);
cout<<suma<<endl;
}
return 0;
}