HDU 1242 Rescue - DFS 回溯
2015-09-04 10:45
267 查看
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1242
这题很经典,值得敲上20遍,刚开始题目理解错误,超时
原来有多个friend,
注意dfs判段
这题很经典,值得敲上20遍,刚开始题目理解错误,超时
原来有多个friend,
注意dfs判段
/* HDU 1242 Rescue http://acm.hdu.edu.cn/showproblem.php?pid=1242 */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> const int MAX = 202; char map[MAX][MAX]; bool visit[MAX][MAX]; int n,m,ax,ay,minx; int fangxiang[4][2] = {{-1,0},{0,-1},{1,0},{0,1}} ; // // 4个方向 上 左 下 右 bool isCanReach(int x , int y) // 坐标是否合理 { if(x >= 0 && x < n && y >=0 && y < m) return true; return false; } void dfs(int x,int y,int len) { if(map[x][y] == 'r') // 找到朋友 需要改变最小值 { if(len < minx) minx = len; return; }else{ if(visit[x][y] || !isCanReach(x,y) || map[x][y] == '#' || len >= minx) // 这里最好加上 len >= minx 判断 ,这样节省时间 return ; visit[x][y] = true; for(int i = 0 ; i < 4 ; i ++) { int nx = x+fangxiang[i][0]; int ny = y + fangxiang[i][1]; if(map[x][y] == 'x') { dfs(nx,ny,len+2); }else{ dfs(nx,ny,len+1); } } visit[x][y] = false; // 回溯 } } int main(){ freopen("in.txt","r",stdin); int i,j,len; while(scanf("%d %d%*c",&n,&m)!=EOF) { for(i=0;i<n;++i) { for(j=0;j<m;++j) { visit[i][j] = false; map[i][j] = getchar(); if(map[i][j]=='a') // 天使的位置 { ax = i; ay = j; } } getchar(); } len = 0; minx = INT_MAX; dfs(ax , ay , len); if(minx != INT_MAX){ printf("%d\n",minx); }else{ printf("Poor ANGEL has to stay in the prison all his life.\n"); } } return 0; }
相关文章推荐
- iOS开发之有趣的UI —— UIScrollerView 控件及案例
- Nqueen1.0
- QSqlQueryModel使用小结
- UIButtont特殊样式
- UILabe的特殊格式
- UIView
- UITextField
- UIImageView以及动画
- Android Studio创建module缺少build文件夹
- String,StringBuffer与StringBuilder的区别??
- 原来UIWindow可以自定义frame
- sort与priority_queue的比较标准差异
- UILabel的文字与 label 的中间线对齐方式
- UILabel.text截取方式
- HDU 1005 Number Sequence(数论)
- POJ 2034 Anti-prime Sequences(数论+dfs)
- POJ 2478 Farey Sequence(欧拉函数)
- PHP基础----PHP常用功能----09include 与 require
- UI控件-----UIScrollView
- Leetcode Unique Binary Search Trees II