题目地址:http://poj.org/problem?id=1979
思路:DFS,暴力搜,把搜过的标记一下就行了。
下面是代码:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int w,h,ans;
char map[25][25];
int dir[4][2]={1,0,-1,0,0,1,0,-1}; //方向(东西南北)
void DFS(int x,int y)
{
for(int i=0;i<4;i++)
{
int xc=x+dir[i][0];
int yc=y+dir[i][1];
if(xc>=0&&xc<h&&yc>=0&&yc<w&&map[xc][yc]=='.')
{
map[xc][yc]='#'; //搜索过的点标记掉,以免重复搜索
ans++;
DFS(xc,yc);
}
}
}
int main()
{
while(cin>>w>>h,w&&h)
{
ans=0;
for(int i=0;i<h;i++)
cin>>map[i];
for(int i=0;i<h;i++)
for(int j=0;j<w;j++)
if(map[i][j]=='@')
{
ans++;
DFS(i,j);
}
cout<<ans<<endl;
}
}