アイデア:
コード1(BFS):
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
# include<queue>
using namespace std;
# define x first
# define y second
typedef pair<int,int> PII;
const int N = 25;
char st[N][N];
int w,h;
int bfs(int sx,int sy)
{
queue<PII> q;
q.push({
sx,sy});
int dx[4] = {
0,0,1,-1},dy[4] = {
1,-1,0,0};
int cnt = 0;
st[sx][sy] = '#';
while(q.size())
{
PII t = q.front();
q.pop();
cnt++;
for(int i = 0;i < 4;i++)
{
int a = t.x + dx[i],b = t.y + dy[i];
if(a < 0 || a >= h || b < 0 || b >= w || st[a][b] != '.') continue;
st[a][b] = '#';
q.push({
a,b});
}
}
return cnt;
}
int main()
{
while(cin >> w >> h,w || h)
{
for(int i = 0;i < h;i++)
{
cin >> st[i];
}
int x,y;
for(int i = 0;i < h;i++)
{
for(int j = 0;j < w;j++)
{
if(st[i][j] == '@')
{
x = i;
y = j;
}
}
}
cout << bfs(x,y) << endl;
}
return 0;
}
コード2(DFS):
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;
const int N = 25;
char st[N][N];
int w,h;
int dfs(int x,int y)
{
int res = 1;
st[x][y] = '#';
int dx[4] = {
0,0,1,-1},dy[4] = {
1,-1,0,0};
for(int i = 0;i < 4;i++)
{
int a = x + dx[i],b = y + dy[i];
if(a >= 0 && a < h && b >= 0 && b < w && st[a][b] == '.')
{
res += dfs(a,b);
}
}
return res;
}
int main()
{
while(cin >> w >> h,w || h)
{
for(int i = 0;i < h;i++)
{
cin >> st[i];
}
int x,y;
for(int i = 0;i < h;i++)
{
for(int j = 0;j < w;j++)
{
if(st[i][j] == '@')
{
x = i;
y = j;
}
}
}
cout << dfs(x,y) << endl;
}
return 0;
}