4 .X.. .... XX.. .... 2 XX .X 3 .X. X.X .X. 3 ... .XX .XX 4 .... .... .... .... 0
5 1 5 2 4
DFS
#include<cstdio> #include<cstdlib> #include<cstring> using namespace std; char map[5][5]; int n,num; int vis[5][5]; int Max(int a,int b) { return a>b?a:b; } bool judge(int x,int y) { int i;if(map[x][y]=='X')return false; for(i=x+1;i<=n;++i) { if(map[i][y]=='X')break; if(vis[i][y])return false; } for(i=x-1;i>0;--i) { if(map[i][y]=='X')break; if(vis[i][y])return false; } for(i=y+1;i<=n;++i) { if(map[x][i]=='X')break; if(vis[x][i])return false; } for(i=y-1;i>0;--i) { if(map[x][i]=='X')break; if(vis[x][i])return false; } return true; } void dfs(int x,int y) { if(x>n) { int k=0; for(int i=1;i<=n;++i) { for(int j=1;j<=n;++j) if(vis[i][j]) { k++; } } num=Max(num,k);return; } if(judge(x,y)) { vis[x][y]=1; if(y+1<=n) dfs(x,y+1); else dfs(x+1,1); vis[x][y]=0; if(y+1<=n) dfs(x,y+1); else dfs(x+1,1); } else { if(y+1<=n) dfs(x,y+1); else dfs(x+1,1); } } int main() { int i,j; while(scanf("%d",&n),n) { for(i=1;i<=n;++i) { scanf("%s",map[i]+1); } num=0; memset(vis,0,sizeof(vis)); dfs(1,1); printf("%d\n",num); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/r1986799047/article/details/47128401