/*
00:42 - 01:17
 */

#include<iostream>
#include<algorithm>
#include<climits>
#include<cstdio>

#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define IINF (INT_MAX)
#define MAX 31
using namespace std;

int H,W;
bool used[MAX][MAX];
char G[MAX][MAX];
int sp,mincost;
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};

inline bool isValid(int x,int y){ return ( 0 <= x && x < W && 0 <= y && y < H); }

void dfs(int cur,int cost,int pdir){

  if(cost >= 10)return;
  if(mincost <= cost)return;
  int x = cur % W, y = cur / W;

  if(G[y][x] == '>'){
    mincost = min(mincost,cost);
    return;
  }

  if(used[y][x])return;

  rep(i,4){
    //if(i == pdir)continue;

    int rnx = x + dx[(i+2)%4], rny = y + dy[(i+2)%4];//次に進む方向の逆
    if( G[rny][rnx] == '#' ){

      used[y][x] = true;
      int nx = x + dx[i], ny = y + dy[i];
      while( G[ny][nx] == '_' ){ 
	if( G[ny+dy[i]][nx+dx[i]] == '^' )break;
	if( G[ny+dy[i]][nx+dx[i]] == '_'){
	  G[ny+dy[i]][nx+dx[i]] = '#';
	  dfs(nx+ny*W,cost+1,(i+2)%4);
	  G[ny+dy[i]][nx+dx[i]] = '_';
	}
	  nx += dx[i], ny += dy[i];
      }
      if( G[ny][nx] == '>' )dfs(nx+ny*W,cost,(i+2)%4);
      if( G[ny][nx] == '#'){
	nx -= dx[i], ny -= dy[i];
	dfs(nx+ny*W,cost,(i+2)%4);
      }
      used[y][x] = false;
    } else if( rnx+rny*W != sp && G[rny][rnx] == '_' ) {
      G[rny][rnx] = '#';
      dfs(cur,cost+1,pdir);
      G[rny][rnx] = '_';
    }
  }
}

int main(){
  int T;
  scanf("%d",&T);
  while(T--){
    scanf("%d %d",&H,&W);
    rep(y,H)rep(x,W){
      cin >> G[y][x];
      if(G[y][x] == 'A')sp = x + y * W, G[y][x] = '_';
      used[y][x] = false;
    }
    
    mincost = IINF;
    dfs(sp,0,IINF);
    if(mincost == IINF)puts("10");
    else               printf("%d\n",mincost);

  }
  return 0;
}