CSES - Shared codeLink to this code:
https://cses.fi/paste/f6db6ab935e23d2072b133/
import sys
from collections import deque
input = sys.stdin.readline
def solve(n, m, grid):
parent = [[None] * m for _ in range(n)]
dirs = [(0, 1, "R"), (1, 0, "D"), (-1, 0, "U"), (0, -1, "L")]
def bfs(pos):
lst = deque([pos])
new_lst = deque()
while lst:
for i, j in lst:
if grid[i][j] != "#":
grid[i][j] = "#"
for x, y, d in dirs:
a, b = i + x, j + y
if 0 <= a < n and 0 <= b < m and grid[a][b] != "#":
new_lst.append((a, b))
parent[a][b] = (i, j, d)
lst = new_lst
new_lst = deque()
a_pos = (0, 0)
b_pos = (0, 0)
for i, row in enumerate(grid):
for j, col in enumerate(row):
if col == "A":
a_pos = (i, j)
elif col == "B":
b_pos = (i, j)
ans = 0
bfs((a_pos[0], a_pos[1]))
x, y = b_pos
if parent[x][y]:
ans = []
while (x, y) != a_pos:
grid[x][y] = "X"
x, y, d = parent[x][y]
ans.append(d)
print("YES")
print(len(ans))
print("".join(reversed(ans)))
else:
print("NO")
def main():
n, m = list(map(int, input().split()))
grid = [list(input().strip()) for _ in range(n)]
solve(n, m, grid)
main()