fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. int dx[4] = {0, 0, -1, 1};
  12. int dy[4] = {-1, 1, 0, 0};
  13. char dir[4] = {'L', 'R', 'U', 'D'};
  14.  
  15. const int N = 1e3 + 5;
  16.  
  17. int n, m;
  18. string grid[N];
  19.  
  20. // dist[0][x][y] = khoảng cách ngắn nhất từ ô xuất phát ('A') đến ô (x, y)
  21. // dist[1][x][y] = khoảng cách ngắn nhất từ một ô có quái vật ('M') đến ô (x, y)
  22. vector<ii> s[2];
  23. int dist[2][N][N];
  24. int p[N][N];
  25.  
  26. bool ok(int x, int y) {
  27. return (0 <= x && x < n && 0 <= y && y < m && grid[x][y] != '#');
  28. }
  29.  
  30. void bfs(int id) {
  31. memset(dist[id], -1, sizeof dist[id]);
  32.  
  33. queue<ii> q;
  34. for (ii u : s[id]) {
  35. int x = u.first, y = u.second;
  36. dist[id][x][y] = 0;
  37. q.push({x, y});
  38. }
  39.  
  40. while (!q.empty()) {
  41. ii u = q.front(); q.pop();
  42. int x = u.first, y = u.second;
  43.  
  44. for (int i = 0; i < 4; i++) {
  45. int nx = x + dx[i], ny = y + dy[i];
  46. if (!ok(nx, ny)) continue;
  47. if (dist[id][nx][ny] == -1) {
  48. dist[id][nx][ny] = dist[id][x][y] + 1;
  49. if (id == 0) p[nx][ny] = i;
  50. q.push({nx, ny});
  51. }
  52. }
  53. }
  54. }
  55.  
  56. // Có thể đến ô (x, y) mà không bị quái vật bắt hay không
  57. bool canEscape(int x, int y) {
  58. return (dist[0][x][y] != -1 && (dist[0][x][y] < dist[1][x][y] || dist[1][x][y] == -1));
  59. }
  60.  
  61. int main() {
  62. ios::sync_with_stdio(false);
  63. cin.tie(nullptr);
  64. cin >> n >> m;
  65.  
  66. for (int i = 0; i < n; i++) {
  67. cin >> grid[i];
  68. for (int j = 0; j < m; j++) {
  69. if (grid[i][j] == 'A') s[0].push_back({i, j});
  70. if (grid[i][j] == 'M') s[1].push_back({i, j});
  71. }
  72. }
  73.  
  74. bfs(0);
  75. bfs(1);
  76.  
  77. int tx = -1, ty = -1;
  78. for (int x = 0; x < n; x++) {
  79. if (canEscape(x, 0)) {tx = x; ty = 0;}
  80. if (canEscape(x, m - 1)) {tx = x; ty = m - 1;}
  81. }
  82.  
  83. for (int y = 0; y < m; y++) {
  84. if (canEscape(0, y)) {tx = 0; ty = y;}
  85. if (canEscape(n - 1, y)) {tx = n - 1; ty = y;}
  86. }
  87.  
  88. if (tx == -1) {
  89. cout << "NO" << '\n';
  90. return 0;
  91. }
  92.  
  93. cout << "YES" << '\n';
  94.  
  95. string path = "";
  96. while (true) {
  97. if (tx == s[0][0].first && ty == s[0][0].second) break;
  98. int i = p[tx][ty];
  99. path += dir[i];
  100. tx -= dx[i], ty -= dy[i];
  101. }
  102.  
  103. reverse(path.begin(), path.end());
  104.  
  105. cout << path.size() << '\n';
  106. cout << path << '\n';
  107. }
Success #stdin #stdout 0.01s 13396KB
stdin
5 8
########
#M..A..#
#.#.M#.#
#M#..#..
#.######
stdout
YES
5
RRDDR