Submission
Status:
-------
Score: 0
User: Dormon
Problemset: Sirabyrinth 1
Language: cpp
Time: 0.002 second
Submitted On: 2024-11-16 20:24:29
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <functional>
#include <queue>
#include <stack>
#define debug(...) Debug(#__VA_ARGS__, __VA_ARGS__)
using namespace std;
template<typename T>
typename std::enable_if<std::is_integral<T>::value>::type
Debug(const char* name, T value) {
std::cout << name << " : " << value << '\n';
}
template<typename T, typename... Args>
typename std::enable_if<std::is_integral<T>::value>::type
Debug(const char* names, T value, Args... args) {
const char* comma = strchr(names, ',');
std::cout.write(names, comma - names) << " : " << value << " | ";
Debug(comma + 1, args...);
}
vector<pair<int, int>> dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
const string S = "URDL";
const int inf = 1e9;
void solve(){
int n, m, a, b; cin >> n >> m;
vector<string> grid(n);
vector<vector<int>> dist(n, vector<int>(m, inf));
for (int i = 0;i < n;i++){
cin >> grid[i];
for (int j = 0;j < m;j++)
if (grid[i][j] == 'S')
a = i, b = j;
}
struct A{
int i, j, w;
};
auto invalid = [&](int i, int j) -> bool {
return i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == '#';
};
queue<A> q;
q.push({a, b, 0});
while (!q.empty()){
auto [i, j, w] = q.front(); q.pop();
if (dist[i][j] != inf) continue;
dist[i][j] = w;
if (i == 0 || i == n-1 || j == 0 || j == m-1){
stack<char> ans;
int ni = i, nj = j;
while (ni != a || nj != b){
for (int x = 0;x < 4;x++){
int di = dir[x].first, dj = dir[x].second;
if (invalid(ni-di, nj-dj)) continue;
if (dist[ni][nj] == dist[ni-di][nj-dj] + 1){
ans.push(S[x]);
ni -= di, nj -= dj;
break;
}
}
}
while (!ans.empty()){
cout << ans.top();
ans.pop();
} cout << '\n';
return ;
}
for (auto [di, dj]:dir){
if (invalid(i+di, j+dj)) continue;
q.push({i+di, j+dj, w+1});
}
}
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
int q = 1; //cin >> q;
while (q--){
solve();
}
}