这道题由于数据量很小,所以直接DFS。注意程序标出来的地方,如果不加else,那么当1处理完以后,又会运行后面的。
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<cmath>
#include<algorithm>
#define N 10
using namespace std;
int n, ans;
int flag_x[N], flag_y[N];
string a[N];
void dfs(int d, int t)
{
if (d == n*n)
{
if (t > ans) ans = t;
return;
}
int x = d / n;
int y = d % n;
if (a[x][y] == 'X' || flag_x[x] == -1 || flag_y[y] == -1) dfs(d+1, t); // 1
else // 注意
{
for (int i = 0; i < 2; i++)
if (i == 1)
dfs(d+1, t);
else
{
int nx = flag_x[x];
int ny = flag_y[y];
if (nx != 1) flag_x[x] = -1;
if (ny != 1) flag_y[y] = -1;
dfs(d+1, t+1);
flag_x[x] = nx;
flag_y[y] = ny;
}
}
}
int main()
{
while (~scanf("%d", &n) && n != 0)
{
memset(flag_x, 0, sizeof(flag_x));
memset(flag_y, 0, sizeof(flag_y));
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (a[i][j] == 'X')
{
flag_x[i] = 1;
flag_y[j] = 1;
}
ans = 0;
dfs(0, 0);
printf("%d\n", ans);
}
return 0;
}