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): 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.
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

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 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· [翻译] 为什么 Tracebit 用 C# 开发
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· 2分钟学会 DeepSeek API,竟然比官方更好用!
· .NET 使用 DeepSeek R1 开发智能 AI 客户端