CSES - Shared codeLink to this code:
https://cses.fi/paste/c7fa7fcb039aa28f72b17f/
import sys
input = sys.stdin.readline
def solve(n, m, grid): # flatten grid to 1d to speed up
parent = [None] * (n * m)
dirs = [(0, 1, "R"), (1, 0, "D"), (-1, 0, "U"), (0, -1, "L")]
def bfs(pos):
lst = [pos]
new_lst = []
while lst:
for p in lst:
i, j = divmod(p, m)
if 0 <= i < n and 0 <= j < m and grid[p] != "#":
grid[p] = "#"
for x, y, d in dirs:
a, b = i + x, j + y
if 0 <= a < n and 0 <= b < m and grid[a * m + b] != "#":
q = a * m + b
new_lst.append(q)
parent[q] = (p, d)
lst = new_lst
new_lst = []
a_pos = 0
b_pos = 0
for i, elem in enumerate(grid):
if elem == "A":
a_pos = i
elif elem == "B":
b_pos = i
ans = 0
bfs(a_pos)
x, y = divmod(b_pos, m)
if parent[b_pos]:
ans = []
while (x, y) != divmod(a_pos, m):
grid[b_pos] = "X"
b_pos, d = parent[b_pos]
x, y = divmod(b_pos, m)
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 = []
for _ in range(n):
grid.extend(input().strip())
solve(n, m, grid)
main()