简单提,只有广搜可以过
#include <iostream>
#include <string>
#include <queue>
using namespace std;
typedef struct
{
int x, y;
char c;
}Node;
int m, n;
char a[501][501];
int d[8][3][2] = {
{{-1,0},{-1,-1},{-1,1}},//n
{{-1,1},{-1,0},{0,1}}, //y
{{0,1},{-1,1},{1,1}}, //e
{{1,1},{0,1},{1,0}}, //q
{{1,0},{1,-1},{1,1}}, //s
{{1,-1},{0,-1},{1,0}}, //j
{{0,-1},{-1,-1},{1,-1}}, //w
{{-1,-1},{0,-1},{-1,0}}//v
};
char chooseDir(int x, int y)
{
if(x==0 && y==-1)
return 'W';
if(x==-1 && y==-1)
return 'V';
if(x==-1 && y==0)
return 'N';
if(x==-1 && y==1)
return 'Y';
if(x==0 && y==1)
return 'E';
if(x==1 && y==1)
return 'Q';
if(x==1 && y==0)
return 'S';
if(x==1 && y==-1)
return 'J';
}
void print()
{
int i, j;
for (i=0; i<n; ++i)
{
for (j=0; j<m; ++j)
{
printf("%c",a[i][j]);
}
printf(" ");
}
}
int main()
{
int i, j;
int x, y;
char dir;
bool flag = false;
queue<Node> mq;
Node st, t, tt;
while (scanf("%d%d",&n, &m) != EOF)
{
if(!flag)
flag = true;
else
printf(" ");
getchar();
for (i=0; i<n; ++i)
{
for (j=0; j<m; ++j)
{
scanf("%c",&a[i][j]);
}
getchar();
}
// print();
scanf("%d %d %c",&x, &y, &dir);
st.x = --x, st.y = --y, st.c = dir;
a[x][y] = dir;
mq.push(st);
while (!mq.empty())
{
t = mq.front();
mq.pop();
//a[t.x][t.y] = t.c;
int index = -1;
if(t.c == 'N')
index = 0;
if(t.c == 'Y')
index = 1;
if(t.c == 'E')
index = 2;
if(t.c == 'Q')
index = 3;
if(t.c == 'S')
index = 4;
if(t.c == 'J')
index = 5;
if(t.c == 'W')
index = 6;
if(t.c == 'V')
index = 7;
int xx, yy;
for (int i=0; i<3; ++i)
{
xx = t.x + d[index][i][0];
yy = t.y + d[index][i][1];
if(xx>=0&&xx<n && yy>=0&&yy<m)
{
if(a[xx][yy]=='X')
{
tt.x = xx;
tt.y = yy;
tt.c = chooseDir(d[index][i][0], d[index][i][1]);
a[xx][yy] = chooseDir(d[index][i][0], d[index][i][1]);
mq.push(tt);
}
}
}
}
print();
}
return 0;
}
本文介绍了一种利用广度优先搜索(BFS)算法解决迷宫路径寻找问题的方法。通过C++实现,详细展示了如何使用队列来遍历地图,并记录每一步的方向选择。适用于理解BFS的基本原理及其在实际问题中的应用。

241

被折叠的 条评论
为什么被折叠?



