Red and Black
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9684 Accepted Submission(s): 6021
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
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#[email protected]#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
[email protected]
###.###
..#.#..
..#.#..
0 0
Sample Output
45
59
6
13
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <string> 5 #include <iomanip> 6 #include <algorithm> 7 #include <queue> 8 #include <vector> 9 #include <map> 10 using namespace std; 11 #define maxn 25 12 #define INF 9999999 13 char mp[maxn][maxn]; 14 struct Node{ 15 int x, y, t; 16 }s; 17 int W, H, sx, sy; //宽,高 18 int dir[4][2] = {{0,1}, {1,0}, {-1,0},{0,-1}}; 19 int timE[maxn][maxn], vis[maxn][maxn]; 20 void BFS(Node start){ 21 queue <Node> Q; 22 Q.push(start); 23 vis[start.x][start.y] = 1; 24 while(!Q.empty()){ 25 Node hd = Q.front(); Q.pop(); 26 for(int i = 0; i < 4; i++){ 27 int nx = hd.x + dir[i][0]; 28 int ny = hd.y + dir[i][1]; 29 if(nx >= 1 && nx <= H && ny >= 1 && ny <= W && mp[nx][ny] != ‘#‘ && !vis[nx][ny]){ 30 Node temp; 31 temp.x = nx; temp.y = ny; temp.t = hd.t+1; 32 vis[nx][ny] = 1; 33 timE[nx][ny] = temp.t; 34 Q.push(temp); 35 36 37 } 38 } 39 } 40 41 } 42 int main(){ 43 while(~scanf("%d%d", &W, &H)){ 44 if(W == 0 || H ==0) break; 45 for(int i = 1; i <= H; i++){ 46 for(int j = 1; j <= W; j++){ 47 cin>>mp[i][j]; 48 if(mp[i][j] == ‘@‘){ 49 s.x = i; 50 s.y = j; 51 s.t = 0; 52 } 53 timE[i][j] = INF; 54 } 55 } 56 timE[s.x][s.y] = 0; 57 memset(vis, 0, sizeof(vis)); 58 BFS(s); 59 int ans = 0; 60 for(int i = 1; i <= H; i ++){ 61 for(int j = 1; j <= W; j++){ 62 if(timE[i][j] != INF) ans++; 63 } 64 } 65 printf("%d\n", ans); 66 } 67 68 return 0; 69 }
hdu 1312 Red and Black(BFS水题),布布扣,bubuko.com