bfs
View Code
#include
<
iostream
>
#include < cstdio >
#include < cstdlib >
#include < cstring >
using namespace std;
#define maxx 1005
#define inc 502
#define maxn maxx * maxx
struct Point
{
int x, y;
} q[maxx * maxx];
int n, cx, cy;
bool vis[maxx][maxx];
bool map[maxx][maxx];
int dist[maxx][maxx];
int dir[ 4 ][ 2 ] =
{
{ 0 , 1 },
{ 1 , 0 },
{ 0 , - 1 },
{ - 1 , 0 } };
bool ok(Point & a)
{
if (a.x < 0 || a.y < 0 || a.x >= maxx || a.y >= maxx)
return false ;
return ! vis[a.x][a.y] && ! map[a.x][a.y];
}
int bfs()
{
int front = 0 ;
int rear = 1 ;
q[ 0 ].x = inc;
q[ 0 ].y = inc;
memset(vis, 0 , sizeof (vis));
vis[inc][inc] = true ;
dist[inc][inc] = 0 ;
while (front != rear)
{
Point a = q[front ++ ];
if (front == maxn)
front = 0 ;
for ( int i = 0 ; i < 4 ; i ++ )
{
Point b;
b.x = a.x + dir[i][ 0 ];
b.y = a.y + dir[i][ 1 ];
if (ok(b))
{
q[rear ++ ] = b;
if (rear == maxn)
rear = 0 ;
dist[b.x][b.y] = dist[a.x][a.y] + 1 ;
vis[b.x][b.y] = true ;
if (b.x == cx && b.y == cy)
return dist[b.x][b.y];
}
}
}
return - 1 ;
}
int main()
{
// freopen("t.txt", "r", stdin);
scanf( " %d%d%d " , & cx, & cy, & n);
cx += inc;
cy += inc;
memset(map, 0 , sizeof (map));
for ( int i = 0 ; i < n; i ++ )
{
int a, b;
scanf( " %d%d " , & a, & b);
a += inc;
b += inc;
map[a][b] = true ;
}
int ans = bfs();
printf( " %d\n " , ans);
return 0 ;
}
#include < cstdio >
#include < cstdlib >
#include < cstring >
using namespace std;
#define maxx 1005
#define inc 502
#define maxn maxx * maxx
struct Point
{
int x, y;
} q[maxx * maxx];
int n, cx, cy;
bool vis[maxx][maxx];
bool map[maxx][maxx];
int dist[maxx][maxx];
int dir[ 4 ][ 2 ] =
{
{ 0 , 1 },
{ 1 , 0 },
{ 0 , - 1 },
{ - 1 , 0 } };
bool ok(Point & a)
{
if (a.x < 0 || a.y < 0 || a.x >= maxx || a.y >= maxx)
return false ;
return ! vis[a.x][a.y] && ! map[a.x][a.y];
}
int bfs()
{
int front = 0 ;
int rear = 1 ;
q[ 0 ].x = inc;
q[ 0 ].y = inc;
memset(vis, 0 , sizeof (vis));
vis[inc][inc] = true ;
dist[inc][inc] = 0 ;
while (front != rear)
{
Point a = q[front ++ ];
if (front == maxn)
front = 0 ;
for ( int i = 0 ; i < 4 ; i ++ )
{
Point b;
b.x = a.x + dir[i][ 0 ];
b.y = a.y + dir[i][ 1 ];
if (ok(b))
{
q[rear ++ ] = b;
if (rear == maxn)
rear = 0 ;
dist[b.x][b.y] = dist[a.x][a.y] + 1 ;
vis[b.x][b.y] = true ;
if (b.x == cx && b.y == cy)
return dist[b.x][b.y];
}
}
}
return - 1 ;
}
int main()
{
// freopen("t.txt", "r", stdin);
scanf( " %d%d%d " , & cx, & cy, & n);
cx += inc;
cy += inc;
memset(map, 0 , sizeof (map));
for ( int i = 0 ; i < n; i ++ )
{
int a, b;
scanf( " %d%d " , & a, & b);
a += inc;
b += inc;
map[a][b] = true ;
}
int ans = bfs();
printf( " %d\n " , ans);
return 0 ;
}