@xunuo
2017-04-14T20:56:24.000000Z
字数 2057
阅读 1168
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
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.
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)
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).
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
45
59
6
13
题意:
一块矩形的地面,贴有红色和黑色的地砖,一个人只能走黑色地砖,能走所在地砖的上,下,左,右四个方向的地砖,给你一个图问总共可以走多少块地砖
解题思路:
一个裸的BFS
完整代码:
#include<bits/stdc++.h>
using namespace std;
int dir[4][2]={0,1,0,-1,1,0,-1,0};///方向;
int vis[25][25];///标记(走过为1,没走为0);
char a[25][25];///存图;
int m,n,num;///m列,n行,走过num个点;
///结构体存点的坐标:
struct node
{
int x;
int y;
};
///从起点开始搜:
int bfs(int x,int y)
{
queue<node>q;
node now,next;
now.x=x;
now.y=y;
q.push(now);
num++;
vis[x][y]=1;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int nx=now.x+dir[i][0];
int ny=now.y+dir[i][1];
if(a[nx][ny]=='.'&&vis[nx][ny]==0&&nx>=0&&nx<n&&ny>=0&&ny<m)
{
next.x=nx;
next.y=ny;
num++;
vis[nx][ny]=1;
q.push(next);
}
}
}
return num;
}
int main()
{
int x,y;
while(scanf("%d%d",&m,&n),m+n)
{
num=0;
memset(a,0,sizeof(a));
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
scanf("%s",a[i]);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
///找起点:
if(a[i][j]=='@')
{
x=i;
y=j;
}
}
printf("%d\n",bfs(x,y));
}
return 0;
}