走迷宫
2015-07-21 18:18
363 查看
#include<iostream> #include<stdio.h> #include<string> #include<cstring> using namespace std; const int Max = 101; bool vis[Max][Max]; int fa[Max][Max],q[Max*Max],dist[Max][Max],last_dir[Max][Max],mat[Max][Max]; int n,m,dx[] = {-1,0,1,0},dy[] = {0,1,0,-1}; char name[] = {'U','D','L','R'}; void bfs(int x,int y) { int front = 0,rear = 0,d,u; u = x*m + y; vis[x][y] = 1;fa[x][y] = u;dist[x][y] = 0; q[rear++] = u; while(front < rear) { u = q[front++]; x=u/m; y=u%m; cout<<"x= "<<x<<" "<<"y= "<<y<<endl; for(d = 0; d < 4; d ++) { int nx = x+dx[d],ny = y + dy[d]; cout<<"nx= "<<nx<<"ny= "<<ny<<endl; if(nx >= 0 && nx <n && ny >= 0 && ny < m && !mat[nx][ny] && !vis[nx][ny]) { cout<<"YYY"<<endl; int v = nx*m+ny; q[rear++]= v; //没办法把图中的节点装进队列,就用v节点记录,放进队列,需要时还原。 vis[nx][ny] = 1; fa[nx][ny] = u; dist[nx][ny] = dist[x][y] + 1; cout<<dist[nx][ny]<<endl; last_dir[nx][ny] = d; } } } } void print_path(int x,int y) { int fx = fa[x][y]/m; int fy = fa[x][y]%m; if(fx != x ||fy != y) { print_path(fx,fy); putchar(name[last_dir[x][y]]); } } int main() { //第一个错误就是n和m重定义。造成bfs里面有了除零错误。。。。。 while(cin>>n>>m) //输入行数和列数 { int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2; //输入其实位置和终止位置 for(int i = 0;i != n; i ++) { for(int j = 0;j != m ; j ++) { cin>>mat[i][j]; //由于是int型输入,所以一定要保证两个数字之间有空格 } } memset(vis,0,sizeof(vis)); memset(dist,0,sizeof(dist)); bfs(x1,y1); cout<<dist[x2][y2]<<endl; print_path(x2,y2); } return 0; }
相关文章推荐
- sql如何查询主键
- 3.Swift翻译教程系列——Swift基础知识
- Java关于集合(list,set,map)的遍历与增强for循环的使用
- [JSON] JSON入门指南
- qt 中文乱码 处理QByteArray类型里含中文的数据
- 常用的Http状态码
- maven 加入json-lib.jar 报错 Missing artifact net.sf.json-lib:json-lib:jar:2.4:compile
- 【iOS开发系列】scrollView中的directionalLockEnabled
- zoj3745 Salary Increasing
- mysql in 子查询 效率慢 优化(转)
- 深入分析C++引用
- juke项目
- 使用LZMA算法(转载)
- jquery获取表单类型为radio的元素
- TEQC最新版本2015年6月23日版本
- Perl的debug小技巧
- 使用基于Http的消息代替WebService的数据交互
- 【Swift】学习笔记(六)——函数
- 工作日志 7.21
- 常用Eclipse插件在线安装地址