#include <iostream>
#include <cstdio>
int w,h;
int array[21][21];
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int dfs(int i,int j)
{
if(i<0||j<0||i>=w||j>=h)
{
return 0;
}
if(array[i][j]=='#')
{
return 0;
}
else
{
array[i][j]='#';
return 1+dfs(i,j-1)+dfs(i,j+1)+dfs(i-1,j)+dfs(i+1,j);
}
}
int main(int argc, char** argv) {
int i,j;
while(scanf("%d %d",&w,&h)&&w>0&&h>0)
{
for(i=0;i<h;i++)
{
scanf("%s",array[i]);
}
for(i=0;i<w;i++)
{
for(j=0;j<h;j++)
{
if(array[i][j]=='@')
{
printf("%d",dfs(i,j));
}
}
}
}
return 0;
}
后来换了一种实现方式,就成功了
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
char a[25][25];
int recur(int x,int y,int H,int W)
{
if(x<0 || x>=H || y<0 || y>=W) return 0;
else
{
if(a[x][y]=='.' || a[x][y]=='@')
{
a[x][y]='#';
return 1+recur(x-1,y,H,W)+recur(x,y-1,H,W)+recur(x+1,y,H,W)+recur(x,y+1,H,W);
}
else return 0;
}
}
int main()
{
int W=0,H=0;
while(cin>>W>>H)
{
if(!W && !H) break;
int x=0,y=0;
int i=0;
while(i<H)
{
int j=0;
while(j<W)
{
cin>>a[i][j];
if(a[i][j]=='@')
{x=i;y=j;}
j++;
}
i++;
}
cout<<recur(x,y,H,W)<<endl;
}
return 0;
}