poj3626

bfs

ContractedBlock.gifExpandedBlockStart.gifView 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;
}

转载于:https://www.cnblogs.com/rainydays/archive/2011/07/13/2105053.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值