1113.红与黑
dfs
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 30;
char g[N][N];
int n,m;
int dfs(int x,int y)
{
int res=1;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
g[x][y]='#';
for (int i=0;i<4;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
if (xx>=0&&xx<n&&yy>=0&&yy<m&&g[xx][yy]=='.')
{
res+=dfs(xx,yy);
}
}
return res;
}
int main()
{
while (cin>>m>>n,m||n)
{
int a,b;
for (int i=0;i<n;i++) scanf("%s",g[i]);
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
{
if (g[i][j]=='@')
{
a=i,b=j;
}
}
printf("%d\n",dfs(a,b));
}
return 0;
}
bfs
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int,int> PII;
#define x first
#define y second
const int N = 30;
char g[N][N];
int n,m;
int st[N][N];
void bfs(PII start,int &ans)
{
queue<PII>q;
q.push(start);
st[start.x][start.y]=1;
while (q.size())
{
PII t=q.front();
q.pop();
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
for (int i=0;i<4;i++)
{
int x=t.x+dx[i];
int y=t.y+dy[i];
if (g[x][y]=='#') continue;
if (st[x][y]!=-1) continue;
if (x<0||x>=n||y<0||y>=m) continue;
ans++;
st[x][y]=1;
q.push({x,y});
}
}
}
int main()
{
while (scanf("%d%d",&m,&n),m||n)
{
memset(st,-1,sizeof st); //注意多组数据,一组结束后需要恢复现场
int ans=1;
for (int i=0;i<n;i++) scanf("%s",g[i]);
PII start;
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
{
if (g[i][j]=='@')
{
start={i,j};
}
}
bfs(start,ans);
printf("%d\n",ans);
}
return 0;
}