bfs求最短路,保持字典序只需要调整广搜的时候的方向优先顺序为D,L,R,U即可,然后打印路径用一个string不断的往下传,传到最后输出返回
#include
#include
#include
#include
#include
#include
using namespace std;
struct p {
int x, y, cou; //cou用来记录走到当前位置走的步数
string str; //str用来记录路径
p() {}
p(int x, int y, string str, int cou) : x(x), y(y), str(str), cou(cou) {}
};
char mapp[510][510];
bool vis[510][510];
queueQ;
int n, m;
//dir按照D,L,R,U的顺序
int dir[4][2] = { {1, 0}, {0, -1}, {0, 1}, {-1, 0} };
bool check(int x, int y) {
if (x <0 || x >= n || y <0 || y >= m || vis[x][y])
return false;
return true;
}
void bfs() {
p tp = p(0, 0, "", 0);
while (!Q.empty()) Q.pop(); //初始化队列
Q.push(tp);
vis[0][0] = true;
while (!Q.empty()) {
p np = Q.front(); Q.pop();
for (int i = 0; i <4; i++) {
int cx = dir[i][0], cy = dir[i][1];
int nx = np.x + cx, ny = np.y + cy;
string ts = "";
if (check(nx, ny)) {
switch(cx) {
case 1: ts = "D"; break;
case -1: ts = "U"; break;
default: break;
}
switch(cy) {
case 1: ts = "R"; break;
case -1: ts = "L"; break;
default: break;
}
if (nx == n - 1 && ny == m - 1) {
cout <cout < return ;
}
Q.push(p(nx, ny, np.str + ts, np.cou + 1));
vis[nx][ny] = true;
}
}
}
}
int main()
{
while (~scanf("%d%d", &n, &m)) {
memset(vis, false, sizeof(vis));
for (int i = 0; iscanf("%s", mapp[i]);
for (int j = 0; jif (mapp[i][j] == '1') vis[i][j] = true;
}
}
bfs();
}
return 0;
}
另外一种记录输出路径的方法:
用一个二维数组记录当前位置前一个点的位置信息,和转向信息,最后用一个栈把结果处理下输出
#include
#include
#include
#include
#include
#include
using namespace std;
struct p {
int x, y, cou; //cou用来记录走到当前位置走的步数
p() {}
p(int x, int y, int cou) : x(x), y(y), cou(cou) {}
};
//node结构体用来保存当前点的前驱位置信息和转向
struct node {
int x, y;
char d;
node() {}
node (int x, int y, char d) : x(x), y(y), d(d) {}
}pre[510][510];
//用于最后输出路径
stacks;
char mapp[510][510];
bool vis[510][510];
queueQ;
int n, m;
//dir按照D,L,R,U的顺序
int dir[4][2] = { {1, 0}, {0, -1}, {0, 1}, {-1, 0} };
bool check(int x, int y) {
if (x <0 || x >= n || y <0 || y >= m || vis[x][y])
return false;
return true;
}
void bfs() {
p tp = p(0, 0, 0);
while (!Q.empty()) Q.pop(); //初始化队列
while (!s.empty()) s.pop();
Q.push(tp);
vis[0][0] = true;
while (!Q.empty()) {
p np = Q.front(); Q.pop();
for (int i = 0; i <4; i++) {
int cx = dir[i][0], cy = dir[i][1];
int nx = np.x + cx, ny = np.y + cy;
char ts;
if (check(nx, ny)) {
switch(cx) {
case 1: ts = 'D'; break;
case -1: ts = 'U'; break;
default: break;
}
switch(cy) {
case 1: ts = 'R'; break;
case -1: ts = 'L'; break;
default: break;
}
if (nx == n - 1 && ny == m - 1) {
pre[nx][ny] = node(np.x, np.y, ts);
cout <
for (int tx, ty; nx != 0 || ny != 0; nx = pre[tx][ty].x, ny = pre[tx][ty].y) {
tx = nx, ty = ny;
s.push(pre[nx][ny].d);
}
while (!s.empty()) {
printf("%c", s.top());
s.pop();
}
puts("");
return ;
}
Q.push(p(nx, ny, np.cou + 1));
pre[nx][ny] = node(np.x, np.y, ts);
vis[nx][ny] = true;
}
}
}
}
int main()
{
while (~scanf("%d%d", &n, &m)) {
memset(vis, false, sizeof(vis));
for (int i = 0; iscanf("%s", mapp[i]);
for (int j = 0; jif (mapp[i][j] == '1') vis[i][j] = true;
}
}
bfs();
}
return 0;
}