/* package workspace; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
    static List<Integer> minSeen = new ArrayList<Integer>();
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		for(int i=0;i<t;i++) {
		    int n = sc.nextInt();
		    int m = sc.nextInt();
		    char[][] arr = new char[n][m];
		    sc.nextLine();
		    int startI = -1;
		    int startJ = -1;
		    for(int j=0;j<n;j++) {
		        int count=0;
		        String str = sc.nextLine();

		        StringTokenizer tok = new StringTokenizer(str, " ");
		        while(tok.hasMoreTokens()) {
		            String s = tok.nextToken();
		            arr[j][count++] = s.charAt(0);
		            if(s.charAt(0) == 'B') {
		                startI = j;
		                startJ = m-1;
		            }
		        }
		    }
		    Map<String, Boolean> tracker = new HashMap<String, Boolean>();
		    catchP(arr, tracker, 0, n, m, startI, startJ);
		    // find min over minSeen here.
		    int min = Integer.MAX_VALUE;
		    for(Integer minI : minSeen) {
		        if( min > minI) {
		            min = minI;
		        }
		    }
		    System.out.println(min);
		}
	}
	
	static boolean seenAlready(Map<String, Boolean> tracker, int n, int m) {
	    String key = Integer.toString(n) + "." + Integer.toString(m);
	    return tracker.containsKey(key);
	}
	
	static boolean isValid(int row, int col, int n, int m) {
	    if( row >= 0 && row <= n-1 && col >=0 && col <= m-1) {
	        return true;
	    }
	    return false;
	}
	
	static void catchP(char[][] arr, Map<String, Boolean> tracker, int len, int n, int m, int startI, int startJ) {
	    Map<String, Boolean> currentTracker = new HashMap<String, Boolean>();
	    if(arr[startI][startJ] == 'C') {
	        minSeen.add(len);
	    } else if ( arr[startI][startJ] == 'D' || arr[startI][startJ]=='.' && seenAlready(tracker, startI, startJ) ) {
	        return;
	    } else if ( arr[startI][startJ]=='.' && !seenAlready(tracker, startI, startJ) || arr[startI][startJ] == 'B' ) {
	        // copy currentTracker same as tracker.
	        tracker.forEach(currentTracker::putIfAbsent);
	        String newKey = Integer.toString(startI) + "." + Integer.toString(startJ);
	        currentTracker.put(newKey, true);
	        if( isValid(startI, startJ-1, n, m)) {
	            catchP(arr, currentTracker, len+1, n, m, startI, startJ-1);
	        }
	        if( isValid(startI-1, startJ, n , m)) {
	            catchP(arr, currentTracker, len+1, n, m, startI-1, startJ);
	        }
	        if( isValid(startI, startJ+1, n, m) ) {
	            catchP(arr, currentTracker, len+1, n, m, startI, startJ+1);
	        }
	        if( isValid(startI+1, startJ, n, m) ) {
	            catchP(arr, currentTracker, len+1, n, m, startI+1, startJ);
	        }
	    }
	}
}
