首页 > 代码库 > hdu--1312--Red and Black (dfs)
hdu--1312--Red and Black (dfs)
Red and Black
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19953 Accepted Submission(s): 12122
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.
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)
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
1 /* 2 Name: hdu--1312--Red and Black 3 Copyright: ?2017 日天大帝 4 Author: 日天大帝 5 Date: 30/04/17 19:19 6 Description: dfs 7 */ 8 #include<iostream> 9 #include<cstring> 10 using namespace std; 11 void dfs(int,int); 12 char map[30][30]; 13 int w,h,ans; 14 int x,y; 15 int dir[4][2] = {0,1,0,-1,1,0,-1,0}; 16 int main(){ 17 ios::sync_with_stdio(false); 18 19 while(cin>>w>>h,w||h){ 20 memset(map,0,sizeof(map)); 21 ans = 0; 22 for(int i=0; i<h; ++i){ 23 cin>>map[i]; 24 for(int j=0; j<w; ++j){ 25 if(map[i][j] == ‘@‘){ 26 x = i;y = j; 27 } 28 } 29 } 30 dfs(x,y); 31 cout<<ans<<endl; 32 } 33 return 0; 34 } 35 void dfs(int x,int y){ 36 ans++; 37 for(int i=0; i<4; ++i){ 38 int xx = x + dir[i][0]; 39 int yy = y + dir[i][1]; 40 if(xx<0 || yy<0 ||xx >=h|| yy>=w|| map[xx][yy] != ‘.‘)continue; 41 map[xx][yy] = ‘#‘; 42 dfs(xx,yy); 43 } 44 }
hdu--1312--Red and Black (dfs)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。