HDU 4528 小明系列故事――捉迷藏 (很好的BFS)
2015-07-30 10:39
381 查看
在用BFS的时候可访问的点要用四个状态去记录,0代表一个都没找到,1代表找到了大明,2代表找到了二明,3代表都找到。
因为在BFS的过程中访问各节点时,因为访问时的状态不同,所以过程中包含有回路。
我的代码:
因为在BFS的过程中访问各节点时,因为访问时的状态不同,所以过程中包含有回路。
我的代码:
#include<cstdio> #include<cstring> #include<queue> #include<iostream> using namespace std; const int maxn = 105; struct Nod{ int x,y,s,t; }; bool vis[maxn][maxn][4]; char ms[maxn][maxn]; int n,m,t; queue<Nod> q; int dx[4] = {1,-1,0,0}; int dy[4] = {0,0,1,-1}; int find(int x,int y){ int res = 0,nx,ny; for(int i=0;i<4;i++){ nx = x + dx[i];ny = y + dy[i]; while(nx <= n && nx >= 1 && ny <= m && ny >= 1 && ms[nx][ny]=='.'){ nx=nx+dx[i];ny=ny+dy[i]; } if(nx <= n && nx >= 1 && ny <= m && ny >= 1){ if(ms[nx][ny]=='D') res+=1; else if(ms[nx][ny]=='E') res+=2; } } return res; } int solve(){ //cout<<find(4,5)<<endl; memset(vis,0,sizeof(vis)); while(!q.empty()) q.pop(); Nod o,ins; for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)if(ms[i][j]=='S'){ o.x = i;o.y = j;o.s = find(i,j);o.t = 0; } q.push(o); vis[o.x][o.y][o.s] = true; while(!q.empty()){ o = q.front();q.pop(); if(o.s==3) return o.t; //printf("%d %d %d %d\n",o.x,o.y,o.s,o.t); int nx,ny,ns; for(int i=0;i<4;i++){ nx = o.x + dx[i];ny = o.y + dy[i]; ns = o.s != find(nx,ny) ? o.s + find(nx,ny) : o.s; if(ns > 3) ns = 3; if(nx < 1 || nx > n || ny < 1 || ny > m || ms[nx][ny] != '.' || vis[nx][ny][ns]) continue; ins.x = nx;ins.y = ny;ins.s = ns;ins.t = o.t + 1; if(ins.t > t) continue; vis[nx][ny][ns] = true; q.push(ins); } } return -1; } int main(){ int cas; scanf("%d",&cas); for(int T = 1 ; T <= cas; T++){ scanf("%d%d%d",&n,&m,&t); for(int i=1;i<=n;i++) scanf("%s",ms[i]+1); printf("Case %d:\n%d\n",T,solve()); } return 0; }
相关文章推荐
- Socket 长连接,短连接以及心跳(keep-alive)概念
- 笔记_一般数据库查询的一个例子Yii
- 2015 多校联赛 ——HDU5325(DFS)
- Android笔记:invalidate()和postInvalidate() 的区别及使用
- UIViewController的presentedViewController,presentingViewController和parentViewController三个属性
- javascript收集连接
- 多线程基础知识
- UVa - The 3n + 1 problem 解读
- [转载] 关于matlab GUI的一点心得
- 深入PHP内核之array_multisort
- Ant 对java webapp打包war 的配置
- 自定义对象的调用
- 从头开始写项目Makefile(一):基本规则
- js dojo 保存txt文件
- 程序员如何爱护自己的眼睛
- 解决多个jquery并存冲突问题
- python积分scipy.integrate
- 对哈夫曼树的一点预习与理解
- iOS 十进制转十六进制
- Hive日期格式转换用法