poj1915

简单题

View Code
   
     
#include < iostream >
#include
< cstdio >
#include
< cstdlib >
#include
< cstring >
#include
< queue >
using namespace std;

struct XPoint
{
int x, y;
int step;

} s, e;

#define maxn 306

int n;
bool vis[maxn][maxn];
int dir[ 8 ][ 2 ] =
{
{
1 , 2 },
{
2 , 1 },
{
- 1 , 2 },
{
- 2 , 1 },
{
- 1 , - 2 },
{
- 2 , - 1 },
{
1 , - 2 },
{
2 , - 1 } };

bool ok(XPoint & b)
{
if (b.x < 0 || b.y < 0 || b.x >= n || b.y >= n)
return false ;
return ! vis[b.x][b.y];
}

void bfs()
{
queue
< XPoint > q;
s.step
= 0 ;
q.push(s);
memset(vis,
0 , sizeof (vis));
vis[s.x][s.y]
= true ;
while ( ! q.empty())
{
XPoint a
= q.front();
q.pop();
for ( int i = 0 ; i < 8 ; i ++ )
{
XPoint b;
b.x
= a.x + dir[i][ 0 ];
b.y
= a.y + dir[i][ 1 ];
b.step
= a.step + 1 ;
if (ok(b))
{
vis[b.x][b.y]
= true ;
q.push(b);
}
if (b.x == e.x && b.y == e.y)
{
printf(
" %d\n " , b.step);
return ;
}
}
}
}

int main()
{
// freopen("t.txt", "r", stdin);
int t;
scanf(
" %d " , & t);
while (t -- )
{
scanf(
" %d " , & n);
scanf(
" %d%d " , & s.x, & s.y);
scanf(
" %d%d " , & e.x, & e.y);
if (s.x == e.x && s.y == e.y)
{
printf(
" 0\n " );
continue ;
}
bfs();
}
return 0 ;
}

你可能感兴趣的:(poj)