搜索—red and black
Description
有一个长方形的房间,铺着方形瓷砖,瓷砖为红色或黑色。一个人站在黑色瓷砖
上,他可以按上、下、左、右方向移动到相邻的瓷砖。但他不能在红色瓷砖上移动,只能在黑色瓷砖上移动。编程计算他可以到达的黑色瓷砖的数量。
Input
输入:第1行包含两个正整数W和H,W和H分别表示x方向和y方向上的瓷砖数量。W和H均不超过20。下面有H行,每行包含W个字符。每个字符表示一片瓷
砖的颜色。用符号表示如下:“●”表示黑色瓷砖;“#”表示红色瓷砖;“@”代表黑色瓷砖上的人,在数据集中只出现一次。
Output
输出:一个数字,这个人从初始瓷砖能到达的瓷砖总数量(包括起点)。
Sample Input
6 9
....#.
.....#
......
......
......
......
......
@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
.###
...@...
.###
..#.#..
..#.#..
0 0
Sample Output
45
59
6
13
More Info
分析
这是一道洪水填充题,从中心点采用bfs逐步由外层扩大。
代码实现
#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
char mp[20][20];
int x,y;
int ans ;
int start_x,start_y;
void dfs(int a,int b){
for(int i = 0;i < 4;i ++){
int xx = a + dir[i][0];
int yy = b + dir[i][1];
if(mp[xx][yy] == '.'&&xx >= 0&&yy >= 0&&xx < x&&yy < y){
ans++;
mp[xx][yy] = '#';
dfs(xx,yy);
}
}
return;
}
int main(){
while(cin>>y>>x){
if(x == 0&&y == 0)break;
memset(mp,0,sizeof(mp));
ans = 1;
for(int i = 0;i < x;i ++)
for(int j = 0;j < y;j ++)
{cin>>mp[i][j];if(mp[i][j] == '@')start_x = i,start_y = j;}
dfs(start_x,start_y);
cout<<ans<<endl;
}
return 0;
}

浙公网安备 33010602011771号