这题让我想起了之前做的八皇后,但是这里还需要判断是否有墙。
#include<stdio.h>
#include<string.h>
int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
char str[5][5];
int map[5][5],count,n,t;
struct node{
int x,y;
}s[17];
int judge(int q){
int flag = 0,dx,dy;
for(int i = 0;i<4;i++){
if(flag) break;
dx = s[q].x + dir[i][0];
dy = s[q].y + dir[i][1];
while(dx>=0 && dy>=0 && dx<n && dy<n){
if(map[dx][dy] == -1) break;
else if(map[dx][dy] == 1){
flag = 1;
break;
}
dx += dir[i][0];
dy += dir[i][1];
}
}
return flag;
}
void dfs(int a,int b){
if(b > count) count = b;
if(a == t) return ;
dfs(a+1,b);
if(!judge(a)){
map[s[a].x][s[a].y] = 1;
dfs(a+1,b+1);
map[s[a].x][s[a].y] = 0;
}
}
int main(){
while(~scanf("%d",&n),n){
getchar();
t = 0;
for(int i = 0;i<n;i++){
for(int j = 0;j<n;j++){
scanf("%c",&str[i][j]);
if(str[i][j] == '.'){
map[i][j] = 0;
s[t].x = i;
s[t].y = j;
t++;
}
else map[i][j] = -1;
}
getchar();
}
count = 0;
dfs(0,0);
printf("%d\n",count);
}
return 0;
}