简单DFS
注意边界就行了。
// #pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define pb(a) push_back(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r void debug() { #ifdef ONLINE_JUDGE #else freopen("d:\\in.txt","r",stdin); freopen("d:\\out1.txt","w",stdout); #endif } char getch() { char ch; while((ch=getchar())!=EOF) { if(ch!=' '&&ch!='\n')return ch; } return EOF; } char da[25][25]; int n,m; int num; int dx[]={-1,0,1,0}; int dy[]={0,1,0,-1}; int vis[25][25]; int dfs(int x,int y) { vis[x][y]=1; num++; for(int d=0;d<4;d++) { int nx=x+dx[d],ny=y+dy[d]; if(da[nx][ny]=='.'&&!vis[nx][ny]&&nx>=1&&nx<=n&&ny>=1&&ny<=m) dfs(nx,ny); } return 0; } int main() { while(scanf("%d%d",&m,&n)!=EOF&&(n||m)) { for(int i=1; i<=n; i++) scanf("%s",da[i]+1); num=0; int bx,by; for(int i=1; i<=n; i++) for(int j=1; j<=m; j++) { if(da[i][j]=='@') { bx=i; by=j; break; } } memset(vis,0,sizeof(vis)); dfs(bx,by); printf("%d\n",num); } return 0; }