利用广度优先搜索,对可以达到的“.”进行统计;
每一个点对应有4个方向,每一个都去尝试
- #include <iostream>
- #include <queue>
- #include <string.h>
- using namespace std;
- struct tile{
- public:
- int x,y;
- void init(int nx,int ny){
- x=nx;
- y=ny;
- }
- };
- char square[21][21];
- int visit[21][21];
- int step[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
- int count(char square[21][21],tile start,int w,int h){
- memset(visit,0,sizeof(visit));
- int x,y,nx,ny,sum=0;
- queue<tile> q;
- q.push(start);
- //cout<<square[1]<<endl;
- while(!q.empty()){
- tile t=q.front();
- q.pop();
- int x=t.x,y=t.y;
- sum++;
- for(int i=0;i<4;i++){ //对4个方向进行统计
- nx=x+step[i][0];
- ny=y+step[i][1];
- if(nx<0||nx>=w||ny<0||ny>=h)continue;
- if(visit[nx][ny])continue;
- if(square[ny][nx]!='.')continue;
- tile c;
- c.init(nx,ny);
- q.push(c);
- visit[nx][ny]=1;
- }
- }
- return sum;
- }
- int main()
- { int w,h,x,y;
- while(cin>>w>>h){
- if(w==0)break;
- for(int i=0;i<h;i++){
- for(int j=0;j<w;j++){
- cin>>square[i][j];
- if(square[i][j]=='@'){
- x=j; //列
- y=i; //行
- }
- }
- }
- tile start;
- start.init(x,y);
- cout<<count(square,start,w, h)<<endl;
- memset(square,' ',sizeof(square));
- }
- return 0;
- }