poj1101
来源:互联网 发布:js获取整数的最大数值 编辑:程序博客网 时间:2024/05/17 04:56
借鉴一些大神的思路后的一点总结,详见代码
方法一:有很大局限性,搜索的方向改变了就wa,可能是测试数据的漏洞,但效率较高
#include<iostream>#include<queue>#include<cstring>using namespace std;int w,h;int to[4][2]={0,1,0,-1,1,0,-1,0};int vis[80][80];char map[80][80];int mini;int x1,y1,x2,y2;struct Node{int x,y,step,dir;//step位所走的大步数,dir为当前状态,1为竖着走,2为横着走};bool operator<(const Node &a,const Node &b){return a.step>b.step;//步数少的优先}int bfs(){memset(vis,0,sizeof(vis));Node s,e;queue<Node>q;s.x=x1;s.y=y1;s.step=0;s.dir=0;vis[s.x][s.y]=1;q.push(s);while(!q.empty()){s=q.front();q.pop();for(int i=0;i<4;i++){e.x=s.x+to[i][0];e.y=s.y+to[i][1];if(e.x==s.x)e.dir=2;//横着走else e.dir=1;//竖着走if(e.x>=0&&e.x<=h+1&&e.y>=0&&e.y<=w+1&&!vis[e.x][e.y]&&(map[e.x][e.y]==' '||(e.x==x2&&e.y==y2))){if(s.dir==0) e.step=1;else{if(s.dir==e.dir) e.step=s.step;else e.step=s.step+1;}if(e.x==x2&&e.y==y2){return e.step;}if(map[e.x][e.y]==' '){vis[e.x][e.y]=1;q.push(e);}}}}return 0;}int main(){int cnt=1;while(cin>>w>>h&&w&&h){memset(map,' ',sizeof(map));int i,j;for(i=1;i<=h;i++){getchar();for(j=1;j<=w;j++) map[i][j]=getchar();}cout<<"Board #"<<cnt++<<':'<<endl;int count=1;while(cin>>y1>>x1>>y2>>x2){if(x1+y1+x2+y2==0)break;cout<<"Pair "<<count++<<": ";int sum=bfs();if(!sum) cout<<"impossible.\n";else cout<<sum<<" segments.\n";}cout<<endl;}return 0;}
方法2:容易理解,无搜索方向局限
#include<iostream>#include<queue>#include<cstring>using namespace std;int w,h;int to[4][2]={-1,0,1,0,0,1,0,-1};int vis[80][80];char map[80][80];int mini;int x1,y1,x2,y2;struct Node{int x,y,step;};void bfs(){memset(vis,0,sizeof(vis));Node s,e;queue<Node>q;s.x=x1;s.y=y1;s.step=0;vis[s.x][s.y]=1;q.push(s);while(!q.empty()){s=q.front();q.pop();if(s.x==x2&&s.y==y2){if(s.step<mini) mini=s.step;//记录最小步数}for(int i=0;i<4;i++){e.x=s.x+to[i][0];e.y=s.y+to[i][1];while(e.x>=0&&e.x<=h+1&&e.y>=0&&e.y<=w+1&&!vis[e.x][e.y]&&(map[e.x][e.y]==' '||(e.x==x2&&e.y==y2))){vis[e.x][e.y]=1;e.step=s.step+1;//该条直线上所有的点的步数相同(遇到X或已访问的节点停止),这样再次搜索时就会改变方向,故步数加1q.push(e);e.x+=to[i][0];e.y+=to[i][1];//沿着该方向一直走}}}}int main(){int cnt=1;while(cin>>w>>h&&w&&h){memset(map,' ',sizeof(map));int i,j;for(i=1;i<=h;i++){getchar();for(j=1;j<=w;j++) map[i][j]=getchar();}cout<<"Board #"<<cnt++<<':'<<endl;int count=1;while(cin>>y1>>x1>>y2>>x2){mini=1000000;if(x1+y1+x2+y2==0)break;cout<<"Pair "<<count++<<": ";bfs();if(mini==1000000) cout<<"impossible.\n";else cout<<mini<<" segments.\n";}cout<<endl;}return 0;}
0 0
- poj1101
- poj1101
- poj1101
- poj1101
- poj1101 The Game
- poj1101解题报告
- poj1101广搜
- 【poj1101】The Game BFS
- poj1101和openjudge 小游戏
- OpenJudge noi 1804小游戏(POJ1101)
- poj1101-The Game(BFS)
- 递归---案例(小游戏poj1101)
- poj1101——The Game//优先队列
- 11.2.3节练习
- Java 写文件:FileOutputStream
- Java中的多线程处理-学习笔记
- 百度地图(一)—————让百度地图显示在自己的软件上
- linux中usb设备的probe注册全过程
- poj1101
- 测试类型介绍
- RT5350SDK与openwrt的区别及基于openwrt定制USB摄像机软件(1)
- html5中viewport浅析
- JSON对象遍历和处理
- zigbee cc2530环境搭建及程序开发大概流程
- AndroidStudio一个工程内查看多个项目的实现
- python高阶函数
- hibernate的映射配置文件