Java 8, 421 408 403 400 351 bytes
int M[][],v[][],l,L;m->{int i=(l=m.length)*(L=m[0].length);for(M=m,v=new int[l][L];m[--i%l][i/l]!=65;);return f(i%l,i/l,-1>>>1,-1);}int z(int x,int y,int r,int d){return x<l&y<L&x>=0&y>=0&&M[x][y]>32&v[x][y]<1?f(x,y,r,d):r;}int f(int x,int y,int r,int d){return M[x][y]>65?r>d?d:r:z(x,y-1,z(x-1,y,z(x,y+1,z(x+1,y,r,d+=v[x][y]=1),d),d),d)+(v[x][y]=0);}
-57 bytes thanks to @ceilingcat.
Input as a matrix of bytes, with A
as start and B
as finish.
Try it online.
Explanation:
int M[][], // Matrix on class-level, starting uninitialized
v[][], // Visited matrix on class-level, starting uninitialized
l,L; // x and y dimensions on class-level, starting uninitialized
m->{ // Method with integer-matrix as input and integer as return
int i=(l=m.length) // Set `l` to the amount of rows
*(L=m[0].length); // Set `L` to the amount of columns
// And set `i` to the product of the two
for(M=m, // Set `M` to the input-matrix
v=new int[l][L]; // Create the visited-matrix filled with 0s
m[--i%l][i/l]!=65;); // Loop as long as the current cell doesn't contain an 'A'
return f( // Start the recursive method `f` with:
i%l,i/l, // The current cell as the starting x,y-coordinate
-1>>>1, // Integer.MAX_VALUE as starting minimum-distance
-1);} // And -1 as amount of steps
int z(int x,int y,int r,int d){
// Method `z` to check whether we can travel to the given cell
return x<l&y<L&x>=0&y>=0// If the x,y-coordinate is within the matrix boundaries,
&&M[x][y]>32 // and that the current cell does NOT contain a space,
&v[x][y]<1? // and we haven't visited this cell yet:
f(x,y,r,d) // Return a call to the recursive method `f` with the same arguments
: // Else:
r;} // Return the row
int f(int x,int y,int r,int d){
// Create the recursive method `f`
return M[x][y]>65? // If the current cell contains 'B':
r>d?d:r // Return the minimum of the min-distance and amount of steps
: // Else:
z(x,y-1, // Do a recursive `z`-call westward,
z(x-1,y, // do a recursive `z`-call northward,
z(x,y+1, // do a recursive `z`-call eastward,
z(x+1,y,r, // do a recursive `z`-call southward,
d+=v[x][y]=1),d),d),d)
// after we've first marked the current cell as visited
+(v[x][y]=0);} // And unmark the current cell as visited afterwards
##
output 0? What should output for##\n++
? \$\endgroup\$