2019 GDUT 新生专题Ⅰ C题

C - DFS/BFS

题目
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
题目大意:一个人在地图上,地图上有黑色格子和红色格子,人可以走黑色格子,不能走红色格子,问此人能走过多少个黑色格子。
思路:典型的bfs题目,用宽搜扫一遍地图,走过的黑色格子标记后不用再走,同时计数。注意人初始位置也是黑色格子。
代码

#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
typedef pair<int,int>P; 
int n,m,vis[25][25],sx,sy,cnt,dx[5]={0,-1,0,1},dy[5]={-1,0,1,0};
char a[25][25];
void bfs(int x,int y){
	queue<P>que;
	que.push(P(x,y));
	while(!que.empty()){
		P p=que.front();
		que.pop();
		for(int i=0;i<4;i++){
			int nx=p.first+dx[i];
			int ny=p.second+dy[i];
			if(a[nx][ny]!='#'&&nx>=0&&ny>=0&&nx<m&&ny<n){
				if(vis[nx][ny]==0&&a[nx][ny]=='.'){
					vis[nx][ny]=1;
					cnt++;
					que.push(P(nx,ny));
				}
			}
		}
	}
}
int main(){
	while(scanf("%d%d",&n,&m)==2&&n&&m){
		for(int i=0;i<m;i++)
		scanf("%s",a[i]);
		for(int i=0;i<m;i++)
		for(int j=0;j<n;j++){
			if(a[i][j]=='@') sx=i,sy=j;
		}
		memset(vis,0,sizeof(vis));
		cnt=1;//人初始位置也是黑色格子,所以初始值为1. 
		bfs(sx,sy);
		printf("%d\n",cnt);
	}
	return 0;
}
[题目链接](http://poj.org/problem?id=1979)
发布了32 篇原创文章 · 获赞 0 · 访问量 655

猜你喜欢

转载自blog.csdn.net/weixin_45794203/article/details/103963324