题意:求一个H*W的地图中一指定的起点的连通的黑色格子有多少个。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312
——>>简单dfs。
#include <cstdio>
using namespace std;
const int maxn = 20 + 10;
char MAP[maxn][maxn];
int W, H, sx, sy, cnt;
int dx[] = {-1, 1, 0, 0};
int dy[] = { 0, 0, -1, 1};
void dfs(int x, int y)
{
for(int i = 0; i < 4; i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx >= 0 && newx < H && newy >= 0 && newy < W && MAP[newx][newy] == '.')
{
MAP[newx][newy] = '#';
cnt++;
dfs(newx, newy);
}
}
}
int main()
{
int i, j;
while(scanf("%d%d", &W, &H) == 2)
{
if(!W && !H) return 0;
for(i = 0; i < H; i++)
{
getchar();
for(j = 0; j < W; j++)
{
MAP[i][j] = getchar();
if(MAP[i][j] == '@')
{
sx = i;
sy = j;
}
}
}
cnt = 1;
dfs(sx, sy);
printf("%d\n", cnt);
}
return 0;
}