DFS水题。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<queue> using namespace std; int dx[] = {0,1,0,-1} ; int dy[] = {1,0,-1,0} ; int n,m,maxn; int vis[25][25]; char s[25][25]; struct pa{ int r,c; }; void bfs(pa a) { queue<pa> q; q.push(a); maxn = 1; memset(vis,0,sizeof(vis)); vis[a.r][a.c] = 1; while(!q.empty()) { pa u = q.front(); q.pop(); for(int i=0;i<4;i++) { pa v ; v.r = u.r+dx[i]; v.c = u.c+dy[i]; if(!vis[v.r][v.c]&&v.r>=0&&v.r<n&&v.c>=0&&v.c<m&&s[v.r][v.c]!='#') { vis[v.r][v.c] = 1; q.push(v); maxn ++ ; } } } } int main() { while(scanf("%d%d",&m,&n)!=EOF) { if(n==0&&m==0) return 0; for(int i=0;i<n;i++) scanf("%s",s[i]); bool ok = false; pa a; for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++) if(s[i][j]=='@') { ok = true; a.r = i; a.c = j; break; } if(ok) break; } bfs(a); printf("%d\n",maxn); } return 0; }
时间: 2024-10-11 07:05:21