poj 2243 (BFS)
2013-09-28 19:19
316 查看
1.使用滚动队列(两个)
2.优化后只使用一个队列
//poj 2243 #include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; typedef struct node { int x; int y; }node; const int SIZE=9; queue<node> Q[2]; int map[SIZE][SIZE], vis[SIZE][SIZE]; node s, t; int dir[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}}; int step; void bfs() { int x, y, tx, ty; node u; int a=0, b=1; step=0; vis[s.x][s.y]=0; if(s.x==t.x && s.y==t.y) return; Q[b].push(s); while(!Q[b].empty()) { swap(a,b); step++; while(!Q[a].empty()) { u=Q[a].front(); Q[a].pop(); x=u.x; y=u.y; for(int i=0;i<8;i++) { tx=x+dir[i][0]; ty=y+dir[i][1]; if(tx<1 || tx>8 || ty<1 || ty>8 || vis[tx][ty]) continue; node v; v.x=tx; v.y=ty; vis[tx][ty]=step; Q[b].push(v); } } } } int main() { int r1, r2; char col1, col2; while(cin>>col1>>r1>>col2>>r2) { memset(vis,0,sizeof(vis)); s.x=r1; s.y=col1-'a'+1; t.x=r2; t.y=col2-'a'+1; bfs(); printf("To get from %c%d to %c%d takes %d knight moves.\n",col1,r1,col2,r2,vis[t.x][t.y]); } return 0; }
2.优化后只使用一个队列
//poj 2243 #include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; typedef struct node { int x; int y; }node; const int SIZE=9; queue<node> Q; int map[SIZE][SIZE], vis[SIZE][SIZE]; node s, t; int dir[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}}; void bfs() { int x, y, tx, ty; node u; vis[s.x][s.y]=0; if(s.x==t.x && s.y==t.y) return; Q.push(s); while(!Q.empty()) { u=Q.front(); Q.pop(); x=u.x; y=u.y; for(int i=0;i<8;i++) { tx=x+dir[i][0]; ty=y+dir[i][1]; if(tx<1 || tx>8 || ty<1 || ty>8 || vis[tx][ty]) continue; node v; v.x=tx; v.y=ty; vis[tx][ty]=vis[x][y]+1; //优化处 Q.push(v); } } } int main() { int r1, r2; char col1, col2; while(cin>>col1>>r1>>col2>>r2) { memset(vis,0,sizeof(vis)); s.x=r1; s.y=col1-'a'+1; t.x=r2; t.y=col2-'a'+1; bfs(); printf("To get from %c%d to %c%d takes %d knight moves.\n",col1,r1,col2,r2,vis[t.x][t.y]); } return 0; }
相关文章推荐
- VC++常用数据类型及其操作详解
- 在nodejs express 中使用session的功能
- 对ARM9哈佛结构的认识
- 常用SQL语句汇总整理
- 10g 创建 Data Guard
- web.xml 中的listener、 filter、servlet 加载顺序及其详解
- linux静态链接库与动态链接库的区别及动态库的创建(转)
- Solaris虚拟机环境搭建
- C#文件后缀名详解
- 工作一年随想
- android私有文件夹的访问
- Exchange 2010 Setup Error – The Exchange Server is in an Inconsistent State
- 位运算 与 生产者消费者
- Arcgis9.3下栅格数据的坐标转换出错
- C#获取当前应用程序所在路径及环境变量
- i2c_add_driver函数用法
- 码农达人开通博客啦
- c\c++ 复习基础要点06---联合体
- 马士兵java视频学习笔记第一章:安装jdk
- java线程