题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1241
这是一个dfs的经典题目,直接进行深度优先搜素就可以解决问题
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
char s[105][105];
int n, m;
void dfs(int x, int y);
int main(void)
{
int i, j;
while(scanf("%d %d", &n, &m))
{
if((n == 0) && (m == 0))
{
break;
}
for(i = 0; i < n; i++)
{
scanf("%s", s[i]);
}
int ans = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(s[i][j] == '@')
{
dfs(i, j);
ans++;
}
}
}
printf("%d\n", ans);
}
return 0;
}
void dfs(int x, int y)
{
s[x][y] = '*';
int dx, dy;
for(dx = -1; dx <= 1; dx++)
{
for(dy = -1; dy <= 1; dy++)
{
int nx = x + dx;
int ny = y + dy;
if((nx<=n)&&(nx>=0)&&(ny<=m)&&(ny>=0)&&(s[nx][ny]=='@'))
{
dfs(nx, ny);
}
}
}
return ;
}