POJ 2243-Knight Moves

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;

}

 

 

你可能感兴趣的:(move)