题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=1312
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
DFS做法:
#include
using namespace std;
const int MAXN = 21;
char a[MAXN][MAXN];
int ans=0;
int m,n;
int x,y;
int d[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
void dfs(int x,int y)
{
a[x][y]='#'; //走过则标记为#
ans++;
int p, q;
for (int i = 0; i < 4; i++)
{
p = x + d[i][0];
q = y + d[i][1];
if (p > 0 && q > 0 && p <= n && q <= m && a[p][q] == '.') //对四个方向进行判断是否走过
{
dfs(p, q); //如果没走过则进行dfs递归
}
}
}
int main()
{
while(cin >> m >> n && m && n)
{
ans = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
{
cin >> a[i][j];
if(a[i][j] == '@')
{
x=i;
y=j;
}
}
dfs(x,y);
cout << ans << endl;
}
return 0;
}
BFS做法:
#include
using namespace std;
char mp[100][100];
int dir[4][2] = {-1,0,0,-1,1,0,0,1}; //方向
int n,m,ans;
#define CHECK(x, y) (x=0 && y >=0 && y//判断是否越界
struct node //把坐标定义成结点
{
int x,y;
};
void bfs(int dx,int dy)
{
ans=1;
queue <node> q; //bfs需要用到队列
node start,next; //开两个结点
start.x = dx;
start.y = dy;
q.push(start); //把第一个结点放入队列
while(!q.empty()) //当队列不为空时
{
start = q.front(); //拿出队列的第一个元素
q.pop(); //删除队列里的第一个元素
for(int i=0; i<4; i++)
{
next.x = start.x + dir[i][0];
next.y = start.y + dir[i][1];
if( CHECK(next.x,next.y) && mp[next.x][next.y]=='.')
{
mp[next.x][next.y] = '#';
ans++;
q.push(next); //把下次走的四个方向放入队列
} //依次循环直至走完所以的点
}
}
}
int main()
{
int x,y,dx,dy;
while(cin >> m >> n && m && n)
{
for (y = 0; y < n; y++)
{
for (x = 0; x < m; x++)
{
cin >> mp[x][y];
if(mp[x][y] == '@')
{
dx = x;
dy = y;
}
}
}
ans=0;
bfs(dx,dy);
cout << ans << endl;
}
return 0;
}