广度优先搜索
#include <iostream>
#include<string>
#include<queue>
using namespace std;
int n, m;
string Map[500];
const int dire[4][2] = { {1,0},{0,-1},{0,1},{-1,0} };
const string d = "DLRU";
struct node
{
int i, j;
string ans;
};
queue<node> q;
void BFS()
{
node s;
s.i = 0, s.j = 0, s.ans = "";
Map[0][0] = '1';
q.push(s);
while (!q.empty())
{
node a = q.front(), b;
int x = a.i;
int y = a.j;
q.pop();
if (x == n - 1 && y == m - 1) {
cout << a.ans.length() << endl;
cout << a.ans << endl;
}
for (int i = 0; i < 4; i++) {
int newx = x + dire[i][0];
int newy = y + dire[i][1];
if (newx < 0 || newx >= n || newy < 0 || newy >= m || Map[newx][newy] == '1') {
continue;
}
b.ans = a.ans + d[i];
b.i = newx, b.j = newy;
Map[b.i][b.j] = '1';
q.push(b);
}
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> Map[i];
}
BFS();
return 0;
}