hdu1312Red and Black(迷宫dfs,一遍)
Red and Black
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 26802 Accepted Submission(s): 16176
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
题意:给出一个类似迷宫的东西,#表示红砖,@表示起点,也是黑砖,点号表示黑砖,每次只能走黑砖,问最多经过多少块黑砖。每次只能走上下左右四个方向
题解:不用剪枝的dfs.....感动.jpg。 就直接看下一个地方能不能走,能走就标记并计数。只要走一遍,所以不需要回溯。因为写的是看下一步能不能走,所以没有算起点,答案就要加1
1 #include<bits/stdc++.h> 2 using namespace std; 3 int w,h; 4 char s[25][25]; 5 int maxx=0; 6 int sx,sy; 7 int dirx[4]={1,-1,0,0},diry[4]={0,0,1,-1}; 8 void dfs(int x,int y) 9 { 10 for(int i=0;i<4;i++) 11 { 12 int xx=x+dirx[i]; 13 int yy=y+diry[i]; 14 if(xx<0||yy<0||xx>=h||yy>=w)continue; 15 if(s[xx][yy]=='.') 16 { 17 s[xx][yy]='#'; 18 maxx++; 19 dfs(xx,yy); 20 } 21 } 22 } 23 int main() 24 { 25 while(~scanf("%d %d",&w,&h),w+h) 26 { 27 maxx=0; 28 memset(s,'\0',sizeof(s)); 29 for(int i=0;i<h;i++) 30 { 31 getchar(); 32 for(int j=0;j<w;j++) 33 { 34 scanf("%c",&s[i][j]); 35 if(s[i][j]=='@') 36 { 37 sx=i; 38 sy=j; 39 } 40 } 41 } 42 dfs(sx,sy); 43 printf("%d\n",maxx+1);//最后答案加1是因为我每次判断下一个是可走的,就+1,这样就没有把起点计算进去 44 } 45 return 0; 46 }