您的位置:首页 > 其它

poj 2243 (BFS)

2013-09-28 19:19 316 查看
1.使用滚动队列(两个)

//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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: