其中的数组输入,要满足自己定义的x,y 的范围,甚是别扭。。。。
Origin:Poj1979
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int w, h, cnt;
char grid[25][25];
int dx[4] = { 0, 0, 1, -1};
int dy[4] = {-1, 1, 0, 0};
inline bool inbound(int x,int y)
{
return (x >= 0&&x<w && y>=0&&y < h);
}
void dfs(int x, int y)
{
if (!inbound(x, y)) return;
else if (grid[x][y] == '@' || grid[x][y] == '.')
{
cnt++;
grid[x][y] = '#';
for (int i = 0; i < 4; i++)
dfs(x + dx[i], y + dy[i]);//深搜,递归
}
}
void solve()
{
memset(grid, 0, sizeof(grid));
int nx = 0, ny = 0; cnt = 0;
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
{
scanf(" %c", &grid[j][i]);
if (grid[j][i] == '@') nx = j, ny = i;
}
dfs(nx, ny);
printf("%d\n", cnt);
}
int main()
{
while (scanf("%d%d", &w, &h)==2 && w && h)
solve();
return 0;
}