我大体是按照算法竞赛入门经典的思路对照写的,可以参考书中的思路对照我的代码。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
#define maxn 1010
queue<int> q;
int n, m;
int maze[maxn][maxn], vis[maxn][maxn], fa[maxn][maxn], dist[maxn][maxn], last_dir[maxn][maxn];
int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
char name[4] = {'U', 'D', 'R', 'L'};
void bfs(int x, int y){
int u = x*m + y;
vis[x][y] = 1; fa[x][y] = u; dist[x][y] = 0; //fa[x][y]存放的是父亲节点的位置(第一个存放的是它本身,在输出时作为结束的条件)
//dist[x][y]表示x,y到出发点的距离;
q.push(u);
while(!q.empty()){
u = q.front();
q.pop();
x = u/m; y = u%m;
for(int i = 0; i < 4; ++i){
int nx = x+dir[i][0], ny = y+dir[i][1];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && !maze[nx][ny] && !vis[nx][ny]){
int v = nx*m + ny;
q.push(v);
vis[nx][ny] = 1;
fa[nx][ny] = u;
dist[nx][ny] = dist[x][y] + 1;
last_dir[nx][ny] = i;
}
}
}
}
void print_path(int x, int y){
int u = fa[x][y];
int fx = u/m, fy = u%m;
if(fx != x || fy != y){
print_path(fx, fy);
putchar(name[last_dir[x][y]]);
}
}
int main()
{
char s[maxn];
scanf("%d%d", &n, &m);
memset(vis, 0, sizeof(vis));
memset(maze, 0, sizeof(maze));
for(int i = 0; i < n; ++i){
scanf("%s", s);
for(int k = 0; k < m; ++k){
maze[i][k] = s[k]-'0';
}
}
bfs(0, 0); //起始位置
print_path(0, m-1); //到达位置
return 0;
}