ACM/ICPC 之 BFS-简单障碍迷宫问题(POJ2935)

时间:2021-08-27 06:38:37

题目确实简单,思路很容易出来,难点在于障碍的记录,是BFS迷宫问题中很经典的题目了。


POJ2935-Basic Wall Maze

  题意:6*6棋盘,有三堵墙,求从给定初始点到给定终点的最短路,输出同一路长的最短路中的任一路径。

  题解:BFS就不说了,对于障碍的记录,我的想法是针对每一个点都记录一次各方向上的情况。比如东边有障碍则在障碍两侧的点增加一个方向数组,用以记录左点的东侧和右点的西侧有障碍,在BFS扩展该方向时,增加一层循环判断一次该方向是否有障碍就行,时间度不会耗费很高,最坏时间度也少于O(4*普通迷宫问题)。

  

 //简单障碍迷宫问题
//三堵墙,6*6棋盘,从给定初始点到给定终点的最短路,输出同一最短路中任一路径
//难点在于阻碍的表示-可增加每个点的阻碍方向记录数组
//Memory:168K Time:0Ms
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std; #define MAX 7 struct Point {
int size; //阻碍方向数
int block[]; //阻碍方向
bool v; //已访问
}board[MAX][MAX]; struct State {
int x, y;
int fa; //记录上一节点
char d; //记录到下一节点方向
}q[MAX*MAX + ]; int sx, sy, ex, ey;
int mov[][] = { {,}, {,}, {,-}, {-,} }; //东南西北
char d[] = "ESWN"; //东南西北 void get_block()
{
int x1, y1, x2, y2;
scanf("%d%d%d%d", &y1, &x1, &y2, &x2);
if (x1 > x2) swap(x1, x2);
if (y1 > y2) swap(y1, y2);
while (y1 == y2 && x1++ < x2) //竖式障碍
{
board[x1][y1].block[board[x1][y1].size++] = ;
int tx = x1 + mov[][];
int ty = y1 + mov[][];
board[tx][ty].block[board[tx][ty].size++] = ;
}
while(x1 == x2 && y1++ < y2) //横式障碍
{
board[x1][y1].block[board[x1][y1].size++] = ;
int tx = x1 + mov[][];
int ty = y1 + mov[][];
board[tx][ty].block[board[tx][ty].size++] = ; }
} //递归输出
void output(State t)
{
if (t.fa){
output(q[t.fa]);
printf("%c", t.d);
}
} void bfs()
{
memset(q, , sizeof(q));
int front = , tail = ;
q[front].x = sx;
q[front].y = sy;
board[sx][sy].v = true;
while (front < tail)
{
int x = q[front].x;
int y = q[front].y;
for (int i = ; i < ; i++)
{
bool flag = true; //可以朝当前方向前进
for (int j = ; j < board[x][y].size; j++)
{
if (i == board[x][y].block[j])
{
flag = false; break;
}
} if (flag) //可以前进
{
State t;
t.x = x + mov[i][];
t.y = y + mov[i][];
t.d = d[i];
t.fa = front;
if (t.x == ex && t.y == ey) //destination
{
output(t);
printf("\n");
return;
}
if (t.x > && t.x < MAX && t.y > && t.y < MAX && !board[t.x][t.y].v)
{
board[t.x][t.y].v = true;
q[tail++] = t;
}
}
}
front++;
}
} int main()
{
while (scanf("%d%d", &sy, &sx), sy && sx)
{
scanf("%d%d", &ey, &ex); memset(board, , sizeof(board));
for (int i = ; i < ; i++)
get_block(); //if (sx == ex && sy == ey)
// printf("\n");
//else
bfs();
} return ;
}