Advertisement
newb_ie

path printing

Nov 14th, 2021
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2.  
  3. using namespace std;
  4.  
  5. int dx[4] = {1, 0, -1, 0};
  6. int dy[4] = {0, 1, 0, -1};
  7. char dir[4] = {'D', 'R', 'U', 'L'};
  8.  
  9. const int maxN = 1010;
  10.  
  11. char grid[maxN][maxN];
  12. bool visited[maxN][maxN];
  13. pair<int,int> parent[maxN][maxN];
  14.  
  15. void bfs (int x, int y, int n, int m) {
  16. queue<pair<int,int>> q;
  17. q.push(make_pair(x, y));
  18. parent[x][y] = {-1, -1};
  19. visited[x][y] = true;
  20. while (!q.empty()) {
  21. pair<int,int> u = q.front();
  22. q.pop();
  23. for (int i = 0; i < 4; ++i) {
  24. int dxx = u.first + dx[i];
  25. int dyy = u.second + dy[i];
  26. if (dxx >= 1 and dxx <= n and dyy >= 1 and dyy <= m and !visited[dxx][dyy] and grid[dxx][dyy] != '#') {
  27. visited[dxx][dyy] = true;
  28. q.push(make_pair(dxx, dyy));
  29. parent[dxx][dyy] = u;
  30. }
  31. }
  32. }
  33. }
  34.  
  35. int main () {
  36. ios::sync_with_stdio(false);
  37. cin.tie(nullptr);
  38. cout.tie(nullptr);
  39. int n, m;
  40. cin >> n >> m;
  41. int start_x, start_y, end_x, end_y;
  42. for (int i = 1; i <= n; ++i) {
  43. for (int j = 1; j <= m; ++j) {
  44. cin >> grid[i][j];
  45. if (grid[i][j] == 'A') {
  46. start_x = i, start_y = j;
  47. }
  48. if (grid[i][j] == 'B') {
  49. end_x = i, end_y = j;
  50. }
  51. }
  52. }
  53. bfs(start_x, start_y, n, m);
  54. if (!visited[end_x][end_y]) {
  55. cout << "NO\n";
  56. } else {
  57. cout << "YES\n";
  58. vector<pair<int, int>> path;
  59. path.push_back(make_pair(end_x, end_y));
  60. int x = end_x, y = end_y;
  61. while (parent[x][y] != make_pair(-1, -1)) {
  62. pair<int,int> p = parent[x][y];
  63. x = p.first, y = p.second;
  64. path.push_back(make_pair(x, y));
  65. }
  66. reverse(path.begin(), path.end());
  67. //~ for (pair<int,int> p : path) {
  68. //~ cout << '{' << p.first << ',' << p.second << "} => ";
  69. //~ }
  70. string res = "";
  71. for (int i = 0; i < (int) path.size() - 1; ++i) {
  72. for (int j = 0; j < 4; ++j) {
  73. int dxx = path[i].first + dx[j];
  74. int dyy = path[i].second + dy[j];
  75. if (dxx == path[i + 1].first and dyy == path[i + 1].second) {
  76. res.push_back(dir[j]);
  77. break;
  78. }
  79. }
  80. }
  81. cout << (int) res.size() << '\n';
  82. cout << res << '\n';
  83. }
  84. }
  85.  
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement