POJ 2243-Knight Moves

本文通过跟着集训手册学习,详细介绍了如何使用BFS算法解决寻找骑士从一个点到另一个点所需步数的问题,并提供了代码实现及实例解析。

http://poj.org/problem?id=2243

我是在看staginner大牛的博客的时候看到这道题的,因为看到了BFS,所以就拿来做了,但是发现

好像之前没写过BFS这玩意,所以就基本照着搬了一遍他的代码,自己写了一下,理解了下队列和广搜。

题目要我们找到从一个点到另一个点的骑士移动的步数,按照staginner的做法是记录在找到终点之前

的所有点到起点的步数。

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;

char a[5], b[5];
int x1, y1, x2, y2;
int dist[10][10], qx[100], qy[100];
int dx[] = { -1, -2, -2, -1, 1, 2, 2, 1};
int dy[] = { -2, -1, 1, 2, 2, -1, 1, -2};

int main()
{
int x, y, nx, ny, front, rear;
while( cin >> a >> b)
{
x1 = a[0] - 'a';
y1 = a[1] - '1';
x2 = b[0] - 'a';
y2 = b[1] - '1';
memset( dist, -1, sizeof( dist) );
dist[x1][y1] = 0;
front = rear = 0;
qx[rear] = x1;
qy[rear] = y1;
rear ++;
while( front < rear)
{
x = qx[front];
y = qy[front];
if( x == x2 && y == y2)
break;
front ++;
for( int i = 0; i < 8; i ++)
{
nx = x + dx[i];
ny = y + dy[i];
if( dist[nx][ny] < 0 && nx >= 0 && nx < 8 && ny >= 0 && ny < 8)
{
dist[nx][ny] = dist[x][y] + 1;
qx[rear] = nx;
qy[rear] = ny;
rear ++;
}
}
}
int steps = dist[x2][y2];
printf( "To get from %s to %s takes %d knight moves.\n", a, b, steps);
}
return 0;
}

跟着集训手册做,又做到了这个题:

/*Accepted    176K    188MS    C++    1287B    2012-07-23 13:27:47*/
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<iostream>
using namespace std;
const int MAXN = 10;
const int dx[] = { 1, 1, -1, -1, 2, 2, -2, -2};
const int dy[] = { 2, -2, 2, -2, 1, -1, 1, -1};
typedef pair<int, int> pii;

int d[MAXN][MAXN];
char a[5], b[5];
int x1, y1, x2, y2;

void bfs()
{
    int i, x, y, nx, ny;
    queue<pii> q;
    pii u;
    d[x1][y1] = 0;
    u.first = x1, u.second = y1;
    q.push(u);
    while(!q.empty())
    {
        u = q.front(); q.pop();
        x = u.first, y = u.second;
        if( x == x2 && y == y2) break;
        for( i = 0; i < 8; i ++)
        {
            nx = x + dx[i];
            ny = y + dy[i];
            if( nx <= 8 && nx > 0 && ny <= 8 && ny > 0 && d[nx][ny] < 0)
            {
                d[nx][ny] = d[x][y] + 1;
                u.first = nx, u.second = ny;
                q.push(u);
            }
        }
    }
}

int main()
{
    while( scanf( "%s%s", a, b) == 2)
    {
        x1 = a[1] - '0';
        y1 = a[0] - 'a' + 1;
        x2 = b[1] - '0';
        y2 = b[0] - 'a' + 1;
        memset( d, -1, sizeof d);
        bfs();
        printf( "To get from %s to %s takes %d knight moves.\n", a, b, d[x2][y2]);
    }
    return 0;
}

 

 

转载于:https://www.cnblogs.com/Yu2012/archive/2011/11/14/2249008.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值