1.07s,tle,BFS算法,不确定原因,根据讨论版已经去掉memset,但是还是不行; 代码在下面:
#include <iostream>
#include <queue>
using namespace std;
const int N = 20;
struct node
{
int x, y, t;
string s;
};
bool vis[N][N]{}, p[N][N]{};
static void bfs(int n, int m)
{
queue <node> q;
q.push({ 1,1,0,"" });
p[1][1] = 1;
int dx[] = { 1,0,-1,0 }, dy[] = { 0,1,0,-1 };
string ds = "DRUL";
while (!q.empty())
{
int x = q.front().x, y = q.front().y, t = q.front().t;
string s = q.front().s;
q.pop();
if (x == n && y == m)
{
cout << t << endl << s << endl;
return;
}
for (int i = 0; i < 4; i++)
{
int _x = x + dx[i], _y = y + dy[i];
if (_x >= 1 && _y >= 1 && _x <= n && _y <= m && (vis[_x][_y] ^ vis[x][y]) && !p[_x][_y])
{
p[_x][_y] = 1;
q.push({ _x,_y,t + 1,s + ds[i] });
}
}
}
cout << -1 << endl;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--)
{
int n, m;
cin >> n >> m;
char c;
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++)
{
vis[i][j] = 0;
p[i][j] = 0;
cin >> c;
if (c == '1') vis[i][j] = 1;
}
bfs(n, m);
}
//system("pause");
return 0;
}