题面传送门:http://poj.org/problem?id=1321
要点:只要想清楚不重复的方法,每次搜索都从放置棋子的下一位开始搜索。(一直向后搜索可以避免重复)
值得一提的是scanf时%c前的空格可以吸收多余的回车。
附上代码:
#include <iostream>
#include <cstdio>
#include <cstring>
int n, k;
const int maxn = 10;
int c[maxn][maxn];
int row[maxn];
int col[maxn];
int num;
using namespace std;
void dfs(int i, int j, int t)
{
if(t == k) num++;
else
{
row[i] = 1;
col[j] = 1;
for (int x = i; x < n; x++)
{
if(row[x]) continue;
int start;
if(x == i) start = j;
else start = 0;
for (int y = start; y < n; y ++)
{
if(col[y]) continue;
if(c[x][y])
{
dfs(x, y, t + 1);
}
}
}
row[i] = 0;
col[j] = 0;
}
}
int main()
{
while(1)
{
scanf("%d%d", &n, &k);
if(n == -1 && k == -1) break;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
char s;
scanf(" %c",&s);
if(s == '#') c[i][j] = 1;
if(s == '.') c[i][j] = 0;
}
}
num = 0;
for(int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if(c[i][j] == 1)
{
memset(row,0,sizeof(row));
memset(col,0,sizeof(col));
dfs(i, j, 1);
}
}
}
printf("%d\n",num);
}
return 0;
}