【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
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0

Sample Output

45
59
6
13

Source

Japan 2004 Domestic

【分析】 典型的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;
}

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/82863775