hdu 1312 Red and Black(DFS)
2015-08-06 22:22
302 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1312
大意:一个人只能在'.'上移动,问@所在地的人能到多少个'.'。
Sample Input
Sample Output
在输入字符数组时候要么用不出错的cin,要么用这样的格式:
getchar();
for(i=1;i<=h;i++)
{
for(j=1;j<=w;j++)
{
scanf("%c",&a[i][j]);
}
getchar();
}
不要用这样的格式:
for(i=1;i<=h;i++)
{
getchar();
for(j=1;j<=w;j++)
{
scanf("%c",&a[i][j]);
}
}
有时这会出错。
来看看两种风格的DFS:
(1):
(2):
大意:一个人只能在'.'上移动,问@所在地的人能到多少个'.'。
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
Sample Output
45 59 6 13
在输入字符数组时候要么用不出错的cin,要么用这样的格式:
getchar();
for(i=1;i<=h;i++)
{
for(j=1;j<=w;j++)
{
scanf("%c",&a[i][j]);
}
getchar();
}
不要用这样的格式:
for(i=1;i<=h;i++)
{
getchar();
for(j=1;j<=w;j++)
{
scanf("%c",&a[i][j]);
}
}
有时这会出错。
来看看两种风格的DFS:
(1):
#include <iostream> #include<cstdio> using namespace std; char s[25][25]; int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; int ans=0; int lie,hang; void dfs(int x,int y){ s[x][y]='#'; ans++; for(int i=0;i<4;i++){ int tx=x+dir[i][0],ty=y+dir[i][1]; if(tx<hang&&tx>=0&&ty<lie&&ty>=0&&s[tx][ty]=='.'){ dfs(tx,ty); } } } int main() { //freopen("cin.txt","r",stdin); while(cin>>lie>>hang){ if(lie==0&&hang==0)break; int x,y; ans=0; for(int i=0;i<hang;i++){ getchar(); for(int j=0;j<lie;j++){ scanf("%c",&s[i][j]); if(s[i][j]=='@'){ x=i; y=j; } } } dfs(x,y); printf("%d\n",ans); } return 0; }
(2):
#include <iostream> #include<cstdio> using namespace std; char a[25][25]; int w,h; int f(int i,int j) { if(i<1||i>h||j<1||j>w) return 0; if(a[i][j]!='#') { a[i][j]='#'; return 1+f(i-1,j)+f(i+1,j)+f(i,j+1)+f(i,j-1); } else return 0; } int main() { //freopen("cin.txt","r",stdin); int i,j; while(~scanf("%d%d",&w,&h)&&w&&h) { int x,y; getchar(); for(i=1;i<=h;i++) { for(j=1;j<=w;j++) { scanf("%c",&a[i][j]); if(a[i][j]=='@'){ x=i; y=j; } } getchar(); } printf("%d\n",f(x,y)); } return 0; }
相关文章推荐
- NOI 2015
- 成都美食记录
- NOI 2015 分类: noi 2015-08-06 22:22 14人阅读 评论(0) 收藏
- 《现代操作系统》精读与思考笔记 第五章 输入/输出
- QString将中文传给std::string
- hadoop知识点总结
- 使用Drawable实时画时钟
- Java ArrayList 初始化
- Unity (三)
- swift public、internal和private
- Yii2 rbac
- 【codevs】p1014 装箱问题
- 一些图片的压缩工具
- java正则表达式入门
- 多线程环境中使用redis
- 微信携手第三方再造新平台 - 公众号第三方平台介绍
- POJ C程序设计进阶 编程题#5:细菌分组实验
- 【黑马程序员】Java笔记--多线程
- ACM学习方法,必备基础
- 3Sum