POJ 1915-Knight Moves

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

这道题还是求骑士从一个点移动到另一个点距离的问题,不同的是棋盘的规格是由我们输入的,

最大有300*300,数组要开足够大,我把2243的代码修改了下就AC了...好好理解下BFS

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

int x1, y1, x2, y2;
int dist[305][305], qx[90005], qy[90005];
int dx[] = { -1, -2, -2, -1, 1, 2, 2, 1};
int dy[] = { -2, -1, 1, 2, 2, -1, 1, -2};

int main()
{
int n, m, nx, ny, x, y, rear, front;
cin >> m;
while( m --)
{
cin >> n;
cin >> x1 >> y1;
cin >> x2 >> y2;
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];
front ++;
if( x == x2 && y == y2)
break;
for( int i = 0; i < 8; i ++)
{
nx = x + dx[i];
ny = y + dy[i];
if( dist[nx][ny] < 0 && nx >= 0 && nx < n && ny >= 0 && ny < n)
{
dist[nx][ny] = dist[x][y] + 1;
qx[rear] = nx;
qy[rear] = ny;
rear ++;
}
}
}
int steps = dist[x2][y2];
cout << steps << endl;
}
return 0;
}

 

今天看了下C ++的STL库,提到了pair,想着去试试。然后写了一遍,STL果然很方便。

#include<iostream>
#include<queue>
#define MAXN 305
using namespace std;
typedef pair< int, int> pii;
int d[MAXN][MAXN], N;
const int dx[] = { 1, 1, 2, 2, -1, -1, -2, -2};
const int dy[] = { 2, -2, 1, -1, 2, -2, 1, -1};
int x1, y1, x2, y2;
void bfs()
{
queue<pii> q;
q.push( make_pair( x1, y1) );
d[x1][y1] = 0;
while( !q.empty() )
{
pii u = q.front(); q.pop();
int x = u.first, y = u.second;
if( x == x2 && y == y2) break;
for( int i = 0; i < 8; i ++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if( d[nx][ny] < 0 && nx >= 0 && nx < N && ny >= 0 && ny < N)
{
d[nx][ny] = d[x][y] + 1;
q.push( make_pair( nx, ny));
}
}
}
}

int main()
{
int cas;
cin >> cas;
while( cas --)
{
cin >> N;
cin >> x1 >> y1;
cin >> x2 >> y2;
memset( d, -1, sizeof d);
bfs();
cout << d[x2][y2] << endl;
}
return 0;
}

 

你可能感兴趣的:(move)