Question Link : Graphs Basic
My Solution :
#include <bits/stdc++.h>
using namespace std;
void solve() {
int m , n;
cin >> m >> n;
vector<vector<char>> arr(m, vector<char>(n));
vector<vector<string>> vis(m, vector<string>(n, "X"));
int sx, sy , ex , ey;
for (int i = 0 ; i < m ; i++) {
for (int j = 0 ; j < n ; j++) {
char ch;
cin >> ch;
arr[i][j] = ch;
if (ch == 'A') {
sx = i;
sy = j;
}
if (ch == 'B') {
ex = i;
ey = j;
}
}
}
int dx[] = { -1, 1, 0, 0};
int dy[] = {0, 0, 1, -1};
queue<pair<int, int>> q;
q.push({sx, sy});
vis[sx][sy] = "";
while (!q.empty()) {
auto top = q.front();
q.pop();
int x = top.first;
int y = top.second;
// cout << x << " " << y << "\n";
for (int k = 0 ; k < 4 ; k++) {
int xx = x + dx[k];
int yy = y + dy[k];
if (xx >= 0 and xx<m and yy >= 0 and yy < n and vis[xx][yy] == "X" and arr[xx][yy] != '#') {
q.push({xx, yy});
if (k == 0) vis[xx][yy] = vis[x][y] + "U";
if (k == 1) vis[xx][yy] = vis[x][y] + "D";
if (k == 2) vis[xx][yy] = vis[x][y] + "R";
if (k == 3) vis[xx][yy] = vis[x][y] + "L";
}
}
}
if (vis[ex][ey] == "X") {
cout << "NO\n";
} else {
cout << "YES\n";
cout << int(vis[ex][ey].size()) << "\n";
cout << vis[ex][ey] << "\n";
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
solve();
return 0;
}
Dont know why i am getting Runtime error