Red and Black(1312)

Problem Description
There is a rectangular room, covered with square tiles.
Each tile is colored either red or black. A man is standing on a black tile.
From a tile, he can move to one of four adjacent tiles. But he can't move on red
tiles, he can move only on black tiles.
Write a program to count the
number of black tiles which he can reach by repeating the moves described above.

Input
The input consists of multiple data sets. A data set
starts with a line containing two positive integers W and H; W and H are the
numbers of tiles in the x- and y- directions, respectively. W and H are not more
than 20.
There are H more lines in the data set, each of which includes W
characters. Each character represents the color of a tile as follows.
'.'
- a black tile
'#' - a red tile
'@' - a man on a black tile(appears
exactly once in a data set)
Output
For each data set, your program should output a line
which contains the number of tiles he can reach from the initial tile (including
itself).
 
题目解说:寻找可以到达的数目是多少。
程序:

#include<iostream>
#include<vector>
#include <cstring>
using namespace std;
int x,y;
char v[30][30];
int fx[4]={0,-1,0,1};
int fy[4]={1,0,-1,0};
int ju[30][30],siz;
struct xy
{
 int xx,yy,ne;
 char v;
};

void BFS(const vector<xy> s,int m)
{
 vector<xy> s1=s;
 if(m>=s1.size())
  return;
 xy w;
 w=s1.at(m);
 int x2,y2,d;char f;
 x2=w.xx;y2=w.yy;f=w.v;d=w.ne;
 
 int x3,y3;
 for(int i=0;i<4;i++)
 {
  x3=x2+fx[i];y3=y2+fy[i];
  if(x3>=0&&x3<x&&y3>=0&&y3<y&&v[x3][y3]=='.'&&ju[x3][y3]==1)
  {
    
   ju[x3][y3]=0;
   w.xx=x3;w.yy=y3;w.v='.';
   w.ne=m;s1.push_back(w);
  }
 }
 if(s1.size()>siz)
  siz=s1.size();
 BFS(s1,m+1);
}
int main()
{
 //freopen("in.txt","r",stdin);
 vector<xy> s;
 xy w;
 while(cin>>y>>x&&(x&&y))
 {
  for(int i=0;i<x;i++)
  {
   for(int j=0;j<y;j++)
   {
    cin>>v[i][j];ju[i][j]=1;
    if(v[i][j]=='@')
    {
     w.xx=i;w.yy=j;w.v='@';
     w.ne=-1;ju[i][j]=0;s.push_back(w);
    }  
   }
  }
  siz=0;
  BFS(s,0);
  s.clear();
  cout<<siz<<endl;
 }
 return 0;
}


 

你可能感兴趣的:(递归,搜索,red,and,black,1312,杭电acm)