Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- int dx[4] = {1, 0, -1, 0};
- int dy[4] = {0, 1, 0, -1};
- char dir[4] = {'D', 'R', 'U', 'L'};
- const int maxN = 1010;
- char grid[maxN][maxN];
- bool visited[maxN][maxN];
- pair<int,int> parent[maxN][maxN];
- void bfs (int x, int y, int n, int m) {
- queue<pair<int,int>> q;
- q.push(make_pair(x, y));
- parent[x][y] = {-1, -1};
- visited[x][y] = true;
- while (!q.empty()) {
- pair<int,int> u = q.front();
- q.pop();
- for (int i = 0; i < 4; ++i) {
- int dxx = u.first + dx[i];
- int dyy = u.second + dy[i];
- if (dxx >= 1 and dxx <= n and dyy >= 1 and dyy <= m and !visited[dxx][dyy] and grid[dxx][dyy] != '#') {
- visited[dxx][dyy] = true;
- q.push(make_pair(dxx, dyy));
- parent[dxx][dyy] = u;
- }
- }
- }
- }
- int main () {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int n, m;
- cin >> n >> m;
- int start_x, start_y, end_x, end_y;
- for (int i = 1; i <= n; ++i) {
- for (int j = 1; j <= m; ++j) {
- cin >> grid[i][j];
- if (grid[i][j] == 'A') {
- start_x = i, start_y = j;
- }
- if (grid[i][j] == 'B') {
- end_x = i, end_y = j;
- }
- }
- }
- bfs(start_x, start_y, n, m);
- if (!visited[end_x][end_y]) {
- cout << "NO\n";
- } else {
- cout << "YES\n";
- vector<pair<int, int>> path;
- path.push_back(make_pair(end_x, end_y));
- int x = end_x, y = end_y;
- while (parent[x][y] != make_pair(-1, -1)) {
- pair<int,int> p = parent[x][y];
- x = p.first, y = p.second;
- path.push_back(make_pair(x, y));
- }
- reverse(path.begin(), path.end());
- //~ for (pair<int,int> p : path) {
- //~ cout << '{' << p.first << ',' << p.second << "} => ";
- //~ }
- string res = "";
- for (int i = 0; i < (int) path.size() - 1; ++i) {
- for (int j = 0; j < 4; ++j) {
- int dxx = path[i].first + dx[j];
- int dyy = path[i].second + dy[j];
- if (dxx == path[i + 1].first and dyy == path[i + 1].second) {
- res.push_back(dir[j]);
- break;
- }
- }
- }
- cout << (int) res.size() << '\n';
- cout << res << '\n';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement