http://lx.lanqiao.cn/problem.page?gpid=T291
各种注意细节
①题目是从1,1开始,编程的时候数组是从0,0开始,各种地方都要记得对应上。
②在使用结构体的map时,要记得在结构体中加上比较,也就是bool operator <(Node obj) const{,否则会发生编译错误。
#include <iostream>
#include <algorithm>
#include <map>
#include <queue>
#include <cstring>
using namespace std;
const int maxn=505;
int n,m;
int G[maxn][maxn];
bool vis[maxn][maxn];
int dir[4][2]={1,0,0,-1,0,1,-1,0};
char D[4]={'D','L','R','U'};
struct Node{
int x,y;
int step;
char path;
bool operator <(Node obj) const{
if (x==obj.x){
return y<obj.y;
}
return x<obj.x;
}
};
void BFS(){
queue <Node> q;
map <Node,Node> M;
Node Now,Tmp;
Now.x=0;
Now.y=0;
Now.step=0;
vis[0][0]=true;
q.push(Now);
while (!q.empty()){
Now=q.front();
q.pop();
if (Now.x==n-1&&Now.y==m-1){
cout << Now.step << endl;
string ans="";
while (Now.x!=0||Now.y!=0){
ans=Now.path+ans;
Now=M[Now];
}
cout << ans << endl;
return;
}
for (int i=0;i<4;i++){
Tmp.x=Now.x+dir[i][0];
Tmp.y=Now.y+dir[i][1];
if (Tmp.x>=0&&Tmp.x<n&&Tmp.y>=0&&Tmp.y<m&&!vis[Tmp.x][Tmp.y]&&G[Tmp.x][Tmp.y]==0){
vis[Tmp.x][Tmp.y]=1;
Tmp.step=Now.step+1;
Tmp.path=D[i];
M[Tmp]=Now;
q.push(Tmp);
}
}
}
}
int main(){
cin >> n >> m;
char ch;
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
cin >> ch;
G[i][j]=ch-'0';
}
}
BFS();
}