Write a program to count the number of black tiles which he can reach by repeating the moves described above.
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)
OutputFor each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0Sample Output
45 59 6 13
解題思路:這是一道bfs的題目,在每次push的時候,就將答案加一
代碼:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int hang,lie;
char a[25][25];
int vis[25][25];
int dis[][2] = {{1,0},{0,1},{-1,0},{0,-1}};
struct node
{
int x;
int y;
};
int ok(int aa,int b)
{
if(aa>=0&&aa<hang&&b>=0&&b<lie&&a[aa][b]=='.')
return true;
else return false;
}
int bfs(node now)
{
int ans = 0;
node help ;
node help2 ;
queue<node> q;
q.push(now);
vis[now.x][now.y] = 1;
while(!q.empty())
{
help = q.front();
q.pop();
for(int i = 0;i<4;i++)
{
help2.x = help.x+dis[i][0];
help2.y = help.y+dis[i][1];
if(!vis[help2.x][help2.y]&&ok(help2.x,help2.y))
{
q.push(help2);
vis[help2.x][help2.y] = 1;
ans++;
}
}
}
return ans;
}
int main()
{
while(cin>>lie>>hang)
{
if(lie==0||hang==0)
break;
memset(vis,0,sizeof(vis));
node pos ;
for(int i = 0;i<hang;i++)
for(int j = 0;j<lie;j++)
{
cin>>a[i][j];
if(a[i][j]=='@')
{
pos.x = i;
pos.y = j;
}
}
int re = bfs(pos);
cout<<re+1<<endl;
}
}