!Light oj 1066--BFS--(队列溢出)
来源:互联网 发布:数据仓apriori算法 编辑:程序博客网 时间:2024/06/16 03:00
题意:走过所有的字母,但必须按照字母的顺序走,求最小的步数
分析:BFS,但是
问题:
1.最开始的各种奇奇怪怪的问题就不写了
2.判断退出的条件最好先写,不然有时会永远也出不去,造成结果为Impossible
3.这题一个点可以走多次,所以必须用一个状态来防止无用的步数放进队列造成空间溢出。
4.新学到的:用坐标和走到该坐标时走过的最后一个字母整体作为一个状态,dis[x][y][chr]
代码:
#include<queue>#include<iostream>#include<cstdio>#include<cstring>using namespace std;int t,n;int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};char a[20][20];struct h{int x,y,g;};queue<h> q;int vis[20][20][30];char JS;int dis[20][20][30];int tx,ty;void bfs(){h tmp;while(!q.empty()){tmp=q.front();int g=tmp.g;q.pop();for(int i=0;i<4;i++){h tmp2;tmp2.x=tmp.x+d[i][0];tmp2.y=tmp.y+d[i][1];if(tmp2.x>=0&&tmp2.x<n&&tmp2.y>=0&&tmp2.y<n&&a[tmp2.x][tmp2.y]!='#'){ if(a[tmp2.x][tmp2.y]=='.'||(a[tmp2.x][tmp2.y]-'A')<=(tmp.g+1)){ int gg=(a[tmp2.x][tmp2.y]-'A')==g+1?g+1:g; if(dis[tmp.x][tmp.y][g]+1<dis[tmp2.x][tmp2.y][gg]){ dis[tmp2.x][tmp2.y][gg]=dis[tmp.x][tmp.y][g]+1; if(!vis[tmp2.x][tmp2.y][gg]){ vis[tmp2.x][tmp2.y][gg]=1; tmp2.g=gg; q.push(tmp2); } } }}}}}int main(){cin>>t;for(int i=1;i<=t;i++){getchar();cin>>n;while(!q.empty()) q.pop();memset(dis,1,sizeof(dis));memset(vis,0,sizeof(vis));JS='A';for(int u=0;u<n;u++) scanf("%s",&a[u]);for(int u=0;u<n;u++)for(int v=0;v<n;v++){if(a[u][v]=='A'){h tmp;tmp.x=u;tmp.y=v;tmp.g=0; dis[u][v][0]=0;q.push(tmp);}if(a[u][v]<='Z'&&a[u][v]>JS){JS=a[u][v];tx=u,ty=v;}}if(JS=='A') cout<<"Case "<<i<<": 0"<<endl;else{bfs();cout<<"Case "<<i<<": ";if(dis[tx][ty][JS-'A']>1e6) cout<<"Impossible"<<endl;else cout<<dis[tx][ty][JS-'A']<<endl;}}}
0 0
- !Light oj 1066--BFS--(队列溢出)
- Light OJ 1066(bfs+坑)
- Light oj 1046 - Rider (BFS)
- Light OJ 1055 BFS
- Light OJ 1141--BFS--(隐蔽的BFS)
- light oj 1066Gathering Food (bfs 稍微有点小坑)
- Light OJ 1238--BFS(第一道自己做的)
- Light OJ 1377 - Blade and Sword (BFS)
- 【Light-oj】-1198 - Karate Competition(贪心+双端队列)
- 【杭电oj】1242-Rescue(bfs,优先队列)
- 【哈工大oj】1621 - 迷宫问题II(bfs,优先队列)
- 【杭电oj】1495 - 非常可乐(bfs,队列)
- 【杭电oj】1253 - 胜利大逃亡(bfs,队列)
- Light OJ:1141 Number Transformation(BFS+素因子)
- Light OJ 1084 线段树+dp or(单调队列+dp) 水题
- light oj(简化复杂度)
- light oj
- light oj
- 汤米维斯提
- 最长回文子串的长度 南邮NOJ 1968
- 得到UIWebView内视频播放器弹出和关闭的通知
- Linux C++ 简单线程池
- SQLServer 服务器架构扩展之数据库扩展的一些步骤
- !Light oj 1066--BFS--(队列溢出)
- 使用通用适配器Base-adapter-helper
- 机器学习常用数据库
- P52 第30题 同构数问题
- apple watch
- Java源代码计算器
- 使用HorizontalScrollView实现侧滑菜单
- Linux进程状态:D
- C和C++中const的区别