hdu1312 Red and Black
Problem 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)
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和DFS应该都可以,不过BFS比较快。
程序说明:
int nxt[][]
:方向数组。
queue<pair<int,int> > que
:BFS的队列,用于扩展点。其中,pair的第一维为x,第二维为y。(也就是坐标)
bool book[]
:标记数组,避免搜索中重复扩展。
code:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int ans=1,n,m,startx,starty,nxt[4][2]={{0,-1},{-1,0},{0,1},{1,0}};
char a[30][30];
bool book[30][30];
void bfs()
{
queue<pair<int,int> > que;
que.push(make_pair(startx,starty));
book[startx][starty]=true;
while(!que.empty())
{
for(int k=0;k<4;k++)
{
int tx=que.front().first+nxt[k][0];
int ty=que.front().second+nxt[k][1];
if(tx<0||tx>=n||ty<0||ty>=m) continue;
if(book[tx][ty]==false&&a[tx][ty]=='.')
{
book[tx][ty]=true;
ans++;
que.push(make_pair(tx,ty));
}
}
que.pop();
}
}
int main()
{
while(~scanf("%d%d",&m,&n)&&(m||n))
{
memset(a,0,sizeof(a));
memset(book,false,sizeof(book));
ans=1;
startx=starty=0;
int flag=0;
for(int i=0;i<n;i++)
{
getchar();
for(int j=0;j<m;j++)
{
a[i][j]=getchar();
if(a[i][j]=='@') startx=i,starty=j;
}
}
bfs();
printf("%d\n",ans);
}
return 0;
}