poj2935

bfs

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

#define maxn 8

struct Wall
{
int s, e;
int p;
bool h;
}wall[
5];

struct Point
{
int x, y;
}s, e, q[maxn
* maxn];

int n = 6;
int step[maxn][maxn];
int from[maxn][maxn];
int dir[4][2] = {{1, 0},{0, 1},{-1, 0},{0, -1}};

void input()
{
scanf(
"%d%d", &e.x, &e.y);
for (int i = 0; i < 3; i++)
{
int a, b, c, d;
scanf(
"%d%d%d%d", &a, &b, &c, &d);
if (a > c)
swap(a, c);
if (b > d)
swap(b, d);
if (a == c)
{
wall[i].h
= false;
wall[i].s
= b + 1;
wall[i].e
= d;
wall[i].p
= a;
}
else
{
wall[i].h
= true;
wall[i].s
= a + 1;
wall[i].e
= c;
wall[i].p
= b;
}
}
}

bool ok(Point &a)
{
if (a.x < 1 || a.y < 1 || a.x > n || a.y > n)
return false;
return step[a.x][a.y] == -1;
}

bool cross(Point a, Point b)
{
if (a.x > b.x)
swap(a, b);
if (a.y > b.y)
swap(a, b);
bool h;
int s, p;
if (a.x == b.x)
{
h
= false;
s
= a.y;
p
= a.x;
}
else
{
h
= true;
s
= a.x;
p
= a.y;
}
for (int i = 0; i < 3; i++)
if (wall[i].h != h && wall[i].p == s && p <= wall[i].e && p >= wall[i].s)
return true;
return false;
}

void bfs()
{
memset(step,
-1, sizeof(step));
memset(from,
-1, sizeof(from));
step[s.x][s.y]
= 0;
q[
0].x = s.x;
q[
0].y = s.y;
int front = 0;
int rear = 1;
while (front != rear)
{
Point a
= q[front++];
Point b;
for (int i = 0; i < 4; i++)
{
b.x
= a.x + dir[i][0];
b.y
= a.y + dir[i][1];
if (ok(b) && !cross(a, b))
{
q[rear
++] = b;
step[b.x][b.y]
= step[a.x][a.y] + 1;
from[b.x][b.y]
= i;
if (b.x == e.x && b.y == e.y)
return;
}
}
}
}

void print()
{
int x = e.x;
int y = e.y;
int stk[maxn * maxn];
int top = 0;
while (from[x][y] != -1)
{
stk[top
++] = from[x][y];
int a, b;
a
= x - dir[from[x][y]][0];
b
= y - dir[from[x][y]][1];
x
= a;
y
= b;
}
char st[10] = "ESWN";
for (int i = top - 1; i >= 0; i--)
putchar(st[stk[i]]);
putchar(
'\n');
}

int main()
{
//freopen("t.txt", "r", stdin);
while (scanf("%d%d", &s.x, &s.y), s.x | s.y)
{
input();
bfs();
print();
}
return 0;
}
原文地址:https://www.cnblogs.com/rainydays/p/2115241.html