HDU1312-DFS

Posted Persistent.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU1312-DFS相关的知识,希望对你有一定的参考价值。

Red and Black

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19690    Accepted Submission(s): 11965


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

 

Sample Output
45
59
6
13
 
 
 
 
代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int direct [4][2]={-1,0,1,0,0,1,0,-1};
 4 char str[25][25];
 5 bool flag[25][25];
 6 int w,h,ans;
 7 void DFS(int x,int y){
 8     for(int i=0;i<4;i++){
 9         int p=x+direct[i][0];
10         int q=y+direct[i][1];
11         if(p>=0&&p<h&&q>=0&&q<w&&flag[p][q]==0&&str[p][q]==\'.\'){
12             ans++;
13             flag[p][q]=1;
14             DFS(p,q);
15         }
16     }
17 }
18 int main(){
19     int Dx,Dy;
20     while(~scanf("%d%d",&w,&h)){
21         if(w==0&&h==0)break;
22         memset(flag,0,sizeof(flag));
23         getchar();
24         for(int i=0;i<h;i++){
25             for(int j=0;j<w;j++){
26                 scanf("%c",&str[i][j]);
27                 if(str[i][j]==\'@\'){
28                     Dx=i;
29                     Dy=j;
30                 }
31             }getchar();
32         }
33         ans=1;
34         flag[Dx][Dy]=1;
35         DFS(Dx,Dy);
36         printf("%d\\n",ans);
37     }
38     return 0;
39 }

 

 

 

 

以上是关于HDU1312-DFS的主要内容,如果未能解决你的问题,请参考以下文章

hdu 1312(DFS)

HDU4057 Rescue the Rabbit(AC自动机+状压DP)

HDU3247 Resource Archiver(AC自动机+BFS+DP)

POJ - 2778 ~ HDU - 2243 AC自动机+矩阵快速幂

微信小程序代码片段

VSCode自定义代码片段——CSS选择器