题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=2
DFS。对于每一个方格都有放或不放两种选择(该方格合法),枚举每一个方格,分放和不放两个方向的搜索。
对于优化问题,就从上一层搜索停下的哪一行开始,没有必要每次都从第一行第一个方格开始。
#include<iostream>
using namespace std;
char city[4][4];
int ans;
int n;
bool OK(int x, int y)
{
if (x>=n || y>=n)
return false;
if (city[x][y] == 'X')
return false;
int xx = x, yy = y;
while (xx < n && city[xx][y] != 'X')
{
if (city[xx][y] == '*')
return false;
xx++;
}
xx = x;
while (xx >= 0 && city[xx][y] != 'X')
{
if (city[xx][y] == '*')
return false;
xx--;
}
while (yy < n && city[x][yy] != 'X')
{
if (city[x][yy] == '*')
return false;
yy++;
}
yy = y;
while (yy >= 0 && city[x][yy] != 'X')
{
if (city[x][yy] == '*')
return false;
yy--;
}
return true;
}
void DFS(int x,int now) //x表示上一层停下的那一行,now表示当前已经有了多少个碉堡
{
ans = now > ans ? now : ans;
for (int i=x; i<n; i++)
for (int j=0; j<n; j++)
if (OK(i,j)) //判断方格的合法性
{
city[i][j] = '*';
DFS(i,now+1);
city[i][j] = '.';
}
}
int main()
{
while (cin>>n && n)
{
for (int i=0; i<n; i++)
for (int j=0; j<n; j++) cin>>city[i][j];
ans = 0;
DFS(0,0);
cout<<ans<<endl;
}
return 0;
}