题意:“@”为起点,“.”为路,求可以走的格子有多少个(包括起点)
水题 bfs搜一发
思路:只有可以走的节点才能进入队列,所以每次出队列时ans+1就可以了(没有退出条件,所有可进入的节点都要搜索)
#include "map" #include "queue" #include "math.h" #include "stdio.h" #include "string.h" #include "iostream" #include "algorithm" #define abs(x) x > 0 ? x : -x #define max(a,b) a > b ? a : b #define min(a,b) a < b ? a : b using namespace std; int d[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; bool Map[25][25],vis[25][25],f[25][25]; int n,m,ans; struct Node { int xx,yy; }; void Bfs(int x,int y) { memset(vis,0,sizeof(vis)); memset(f,0,sizeof(f)); Node now,next; queue<Node>Q; now.xx = x; now.yy = y; vis[x][y] = 1; f[x][y] = 1; ans = 0; Q.push(now); while(!Q.empty()) { now = Q.front(); Q.pop(); if(Map[now.xx][now.yy]) ans++; for(int i=0; i<4; i++) { next.xx = now.xx + d[i][0]; next.yy = now.yy + d[i][1]; if(Map[next.xx][next.yy] && !vis[next.xx][next.yy]) { vis[next.xx][next.yy] = 1; Q.push(next); } } } printf("%d ",ans); } int main() { int i,j,x,y; char c; while(scanf("%d%d",&n,&m)&&(n||m)) { memset(Map,0,sizeof(Map)); for(i=1; i<=m; i++) { getchar(); for(j=1; j<=n; j++) { scanf("%c",&c); if(c=='#') Map[i][j] = 0; if(c=='.') Map[i][j] = 1; if(c=='@') { x=i,y=j; Map[i][j] = 1; } } } Bfs(x,y); } return 0; }