Double Maze
2014-03-18 21:49
323 查看
题目描述
一个迷宫里,有两个点,你的任务是给出尽可能短的一系列的命令,让这两个点一起执行这些命令能走到一起。如果某个点按某个命令走会走出迷宫或走到障碍上,则忽略这条命令。
输入
输入不超过1000个样例,每个样例第一行有两个整数n,m(2≤n,m≤11),之后n行每行m个字符,'.'表示能走的地方,'#'表示障碍,‘*'表示其中一个点。每个样例之间有一个空行。
输出
每个样例输出一行,包含'U','D','L','R'。'U'表示向上走的命令,'D'表示向下,'L'表示向左,'R'表示向右。要是有多个答案,输出字典序最小的序列。如果无法达到目标,输出“Sorry”(引号不要输出)。
样例输入
4 11 *.##..#..#* ...#..#.#.. .##.#.#.##. ##..###.... 4 4 .*.. .### ...* .... 10 10 *......... #########. .......... .######### .......... #########. .......... .######### .........* ##########
样例输出
Sorry LLLUU LLLLLLLLLUURRRRRRRRRUULLLLLLLLLUURRRRRRRRRDD
题解:用BFS搜索,并比较走过路劲的大小,用哈希把路径存储下来。输出最短路径即可。
#include <cstdio> #include <iostream> #include <cstring> #include <set> #include <queue> using namespace std; int a,b,c,d,n,m,i,j; int x[4]={1,0,0,-1}; int y[4]={0,-1,1,0}; char z[4]={'D','L','R','U'}; char s[20][20]; void check(int& x1,int& y1,int& x2,int& y2,int i) { if (x1<0 || x1>=n || y1<0 || y1>=m || s[x1][y1]=='#') { x1-=x[i]; y1-=y[i]; } if (x2<0 || x2>=n || y2<0 || y2>=m || s[x2][y2]=='#') { x2-=x[i]; y2-=y[i]; } } int hash(int a,int b,int c,int d) { int k=a; k=k*100+b; k=k*100+c; k=k*100+d; return k; } struct zb { int x1,y1,x2,y2; string ss; }; int main() { while (~scanf("%d%d",&n,&m)) { set <int> st; queue <zb> q; st.clear(); a=0;b=0;c=0;d=0; getchar(); for (i=0;i<n;i++) scanf("%s",s[i]); for (i=0;i<n;i++) for (j=0;j<m;j++) if (s[i][j]=='*') if (a==0 && b==0) { a=i; b=j; } else { c=i; d=j; break; } int k=hash(a,b,c,d); st.insert(k); zb qq=(zb){a,b,c,d,"."}; q.push(qq); int flag=0; string ans; while (!q.empty()) { qq=q.front(); q.pop(); if (flag && (qq.ss.size()>ans.size())) break; if (qq.x1==qq.x2 && qq.y1==qq.y2) { // cout<<ans<<endl; if (ans.size()==0) ans=qq.ss; else if (ans.size()>qq.ss.size()) ans=qq.ss; flag=1; } for (i=0;i<4;i++) { int X1=qq.x1+x[i],X2=qq.x2+x[i]; int Y1=qq.y1+y[i],Y2=qq.y2+y[i]; check(X1,Y1,X2,Y2,i); string sss=qq.ss+z[i]; k=hash(X1,Y1,X2,Y2); if (!st.count(k)) { st.insert(k); zb ww=(zb){X1,Y1,X2,Y2,sss}; q.push(ww); } } } if (flag) { for (i=1;i<ans.size();i++) printf("%c",ans[i]); printf("\n"); } else printf("Sorry\n"); } return 0; }
相关文章推荐
- QtCreator使用时需要注意的一个地方。
- oracle 聚组函数
- 【DFS】Combinations
- SSH2学习笔记
- Mfc Tips
- 最长不重复子串
- 黑马程序员 《ios零基础教程》-- ”Mac OS X的介绍”和一些“基础语法” 2014-3-18总结
- get 新技能
- adb命令安装和卸载apk文件
- OpenGL开发前的准备——开发环境的配置
- Android游戏开发 study 4-5
- HighCharts之2D柱状图
- QQ免费企业邮箱申请配置
- HighCharts之2D柱状图
- 【转】测试过程管理案例6---如何做项目的测试经理?
- QQ免费企业邮箱申请配置
- 解决在Linux中SQL方向键和退格键不能使用问题
- 闲扯LUA之一
- ZOJ-2165
- 内存泄露和内存溢出区别