poj 2243 (BFS)

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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值