HDU 1312 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
这道题的意思是说,一个房间里有两张瓷砖,一种红色(用#表示),一种黑色(用 . 表示)。一个人在房间里走,只能在黑色瓷砖上走,一次只能达到相邻的四块瓷砖,问,这个人做多能走过多少块瓷砖?
使用深搜,一步一步走就行了,水  ̄へ ̄
直接上代码了 (~ ̄▽ ̄)~
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int w ,h, ans;
char a[25][25];
int vis[25][25];
int dir[4][2]={{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
void dfs(int x, int y)
{
int nx, ny;
for (int i = 0; i < 4; i++)
{
nx = x + dir[i][0];
ny = y + dir[i][1];
if (a[nx][ny] == '.' && nx >= 0 && nx < h && ny >= 0 && ny < w && !vis[nx][ny])
{
vis[nx][ny] = 1;
dfs(nx, ny);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1.txt", "r", stdin);
#endif
int i, j;
while(scanf("%d%d", &w, &h), w)
{
memset(a, 0, sizeof(a));
for(i = 0; i < h; i++)
{
scanf("%s", a[i]); //gets{a[i])为什么WA??? why???
}
ans = 0;
memset(vis, 0, sizeof(vis));
for (i = 0; i < h; i++)
{
for (j = 0; j < w; j++)
{
if (a[i][j] == '@')
{
vis[i][j] = 1;
dfs(i, j);
break;
}
}
}
for (i = 0; i < h; i++)
{
for (j = 0; j < w; j++)
{
ans += vis[i][j];
}
}
cout << ans << endl;
}
return 0;
}