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
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#[email protected]#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
[email protected]
###.###
..#.#..
..#.#..
0 0
Sample Output
45
59
6
13
题目大意:
一个瓦片地图,‘.‘代表黑色的瓦片,‘#‘代表红色的瓦片,‘#‘是主人公站的位置,主人公只会下上左右四种移动方式,且只能去黑色的瓦片(初始位置也是黑色的瓦片);
求可以去的黑色瓦片个数,包括初始位置。
结题思路:
简单的DFS,搜索一下与初始位置上下左右相连的所有黑色瓦片,并记录输出即可。
Code;
1 #include<iostream> 2 #include<string> 3 #include<cstdio> 4 #define MAXN 50 5 using namespace std; 6 bool vis[MAXN+10][MAXN+10],is_black[MAXN+10][MAXN+10]; //黑色瓦片标记 7 char tile[MAXN+10][MAXN+10]; 8 int n,m; 9 int dfs(int i,int j) 10 { 11 12 if (is_black[i][j]==0||vis[i][j]==1) return 0; //搜索时遇到已经搜索过的或者红色瓦片则返回,不记录瓦片数。 13 vis[i][j]=1; 14 int sum=1; 15 if (i-1>=1) sum+=dfs(i-1,j); //搜索上下左右四种情况 16 if (i+1<=n) sum+=dfs(i+1,j); 17 if (j-1>=1) sum+=dfs(i,j-1); 18 if (j+1<=m) sum+=dfs(i,j+1); 19 return sum; 20 } 21 int main() 22 { 23 int first_i,first_j; 24 while (cin>>m>>n) 25 { 26 if (m==0&&n==0) break; 27 memset(is_black,0,sizeof(is_black)); 28 memset(vis,0,sizeof(vis)); 29 getchar(); 30 for (int i=1; i<=n; i++) 31 { 32 for (int j=1; j<=m; j++) 33 { 34 cin>>tile[i][j]; 35 if (tile[i][j]==‘@‘) first_i=i,first_j=j,tile[i][j]=‘.‘; //记录初始位置用于调用DFS,并用题意将初始位置转换成黑色瓦片(貌似没有必要--!) 36 if (tile[i][j]==‘#‘) is_black[i][j]=0;//用Is_Black数组标记瓦片颜色 37 else is_black[i][j]=1; 38 } 39 getchar(); 40 } 41 42 printf("%d\n",dfs(first_i,first_j)); 43 } 44 return 0; 45 }
HDU1312——Red and Black