您的位置:首页 > 其它

POJ 2935 Basic Wall Maze

2015-03-09 01:31 274 查看

POJ 2935 Basic Wall Maze

1 算法

简单的BFS,但WA了好久。
队列q保存BFS过程中的节点的坐标(x,y),父节点的地址father, 和父节点到达当前节点所走的方向c, 输出路径时根据目标节点的father索引回源节点。

2 代码

2.1 WA的代码

#Problem: 2935
#Memory: N/A		Time: N/A
#Language: G++		Result: Wrong Answer
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

struct way
{
struct way *father;
int x, y;
char c;
};

int sx, sy;
int tx, ty;
struct way q[100];
int qf, ql;
int offsetx[4] = {0, 0, 1, -1};
int offsety[4] = {-1, 1, 0, 0};
bool wall[8][8][8][8];
char direction[4] = {'N', 'S', 'E', 'W'};
bool isv[7][7];

void read_data()
{
int x1, y1, x2, y2;
cin >> tx >> ty;
memset(wall, 0, sizeof(wall));
for (int i = 0; i < 3; ++i)
{
cin >> x1 >> y1 >> x2 >> y2;
if (x1 == x2)
{
if (y1 > y2) swap(y1, y2);
for (int k = y1 + 1; k <= y2; ++k)
{
wall[x1][k][x1 + 1][k] = true;
wall[x1 + 1][k][x1][k] = true;
}
}
if (y1 == y2)
{
if (x1 > x2) swap(x1, x2);
for (int k = x1 + 1; k <= x2; ++k)
{
wall[k][y1][k][y1 + 1] = true;
wall[k][y1 + 1][k][y1] = true;
}
}
}
}

bool isinside(int x, int y)
{
return (1 <= x && x < 7 && 1 <= y && y < 7);
}

void print(struct way *p)
{
if (p == NULL) return ;
print(p->father);
printf("%c", p->c);
}

void bfs()
{
int fx, fy;
int nx, ny;
qf = ql = 0;
q[ql].father = NULL;
q[ql].x = sx;
q[ql].y = sy;
memset(isv, 0, sizeof(isv));
isv[sx][sy] = true;
ql++;
while (qf != ql)
{
fx = q[qf].x;
fy = q[qf].y;
for (int i = 0; i < 4; ++i)
{
nx = fx + offsetx[i];
ny = fy + offsety[i];
if (isinside(nx, ny) && !isv[nx][ny] &&
!wall[nx][ny][fx][fy])
{
q[ql].x = nx;
q[ql].y = ny;
q[ql].father = &(q[qf]);
q[ql].c = direction[i];
if (nx == tx && ny == ty)
{
print(&(q[ql]));
return ;
}
ql++;
isv[nx][ny] = true;
}
}
qf++;
}
}

int main()
{
cin >> sx >> sy;
while (sx != 0 && sy != 0)
{
read_data();
bfs();
printf("\n");
cin >> sx >> sy;
}
return 0;
}

2.2 修改

62行
if (p == NULL) return ;

改为
if (p->father == NULL) return ;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: