标签:des style blog color os strong io for
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.
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
题目大意:
给出两个数m和n,代表n行m列,都不超过20,然后是n行m列的图,包括‘.‘ , ‘#‘ , ‘@‘3个字符。
@代表初始位置,‘.‘代表通路,‘#’代表墙,求最大可到达的 ‘.‘ 的数量 ‘@‘算一个
BFS:
即求最大连通块问题 不一定非要用队列 一维数组一样可以解决
1 #include<stdio.h> 2 #include<string.h> 3 struct node 4 { 5 int x,y; 6 }q[410]; 7 8 struct node P, N; 9 int flag[25][25]; 10 int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; 11 char str[25][25]; 12 13 int main() 14 { 15 int c, r, i, j, front, rear; 16 while(scanf("%d%d",&c,&r)!=EOF, c + r){ 17 memset(flag, 0, sizeof(flag)); 18 for(i = 0; i < r; i++) 19 scanf("%s", str[i]); 20 21 for(i = 0; i < r; i++){ 22 for(j=0;j<c;j++) 23 if(str[i][j] == ‘@‘) break; 24 if(str[i][j] == ‘@‘) break; 25 } 26 N.x = i; 27 N.y = j; 28 flag[i][j] = 1; 29 q[0] = N; 30 front = 0; 31 rear = 1; 32 33 while(front < rear){ 34 N = q[front++]; 35 for(i = 0; i < 4; i++){ 36 int tx = N.x + dir[i][0]; 37 int ty = N.y + dir[i][1]; 38 if(tx >= 0 && tx < r && ty >= 0&& ty < c && flag[tx][ty] == 0 && str[tx][ty] == ‘.‘){ 39 P.x = tx; 40 P.y = ty; 41 q[rear++] = P; 42 flag[tx][ty] = 1; 43 } 44 } 45 } 46 printf("%d\n",rear); 47 } 48 return 0; 49 }
ZOJ 2165 Red and Black,布布扣,bubuko.com
标签:des style blog color os strong io for
原文地址:http://www.cnblogs.com/zzy9669/p/3884439.html