Skip to main content
5 of 5
saved 5 bytes
Arnauld
  • 205.5k
  • 21
  • 187
  • 670

JavaScript (ES6), 171 bytes

Expects a matrix of characters.

f=(m,X,Y=o=f,e=1,n=0)=>m.map((r,y)=>r.map((c,x)=>!~(j="RULD #".search(c))|(n+=j==4,X+1?j>4|(h=x-X)*h+(v=y-Y)*v^1:j<5)?0:j<4?e=j^(v&2)-~h:r[f(m,r[x]=x,y),x]=c))|e|n>o?o:o=n 

Try it online! (only the fastest test cases)

Arnauld
  • 205.5k
  • 21
  • 187
  • 670