【POJ】1979 Red and Black(BFS)
Red and Black
Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 44023 Accepted: 23850 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) The end of the input is indicated by a line consisting of two zeros.
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).
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#[email protected]#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### [email protected] ###.### ..#.#.. ..#.#.. 0 0Sample Output
45 59 6 13Source
【分析】 典型的bfs題啦。然後要注意一下細節。vis陣列的初始化每次都要有,bfs不同於dfs,沒有遞迴,一次只是執行一次迴圈,所以,在bfs函式內進行陣列的初始化。emmm還有就是程式碼規範問題,寫結構體就順帶著把建構函式寫了吧~ 結構體賦值的時候也不要直接類似於s={x,y}這樣寫,有時候會報錯。還有就是,佇列元素要先取出來再彈出去,不可以不取就彈!!
【程式碼】
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct node{
int x,y;
node(){}
node(int a,int b)
{
x=a;y=b;
}
};
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int vis[25][25];
char mp[25][25];
int num,w,h;
int bfs(int x,int y)
{
memset(vis,0,sizeof(vis));
queue<node>q;
q.push(node(x,y));
while(!q.empty())
{
x=q.front().x;y=q.front().y;
q.pop();
// num++;cout<<num<<endl;
if(vis[x][y])continue;
vis[x][y]=1;
num++;
for(int i=0;i<4;i++)
{
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(xx<0||xx>=h||yy<0||yy>=w)continue;
if(vis[xx][yy])continue;
if(mp[xx][yy]=='#')continue;
q.push(node(xx,yy));
}
}
return num;
}
int main()
{
while(~scanf("%d%d",&w,&h)&&w&&h)
{
for(int i=0;i<h;i++)
scanf("%s",mp[i]);
int flag=0;
num=0;
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
if(mp[i][j]=='@')
{
cout<<bfs(i,j)<<endl;
flag=1;break;
}
}
if(flag)break;
}
}
return 0;
}