/*
BFS+模拟:dp[i][j][p] 表示走到i,j,方向为p的步数为多少;
BFS分4种情况入队,最后在终点4个方向寻找最小值:)
*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
using namespace std; const int MAXN = 1e2 + ;
const int INF = 0x3f3f3f3f;
int dir[][][] = {
{{, -}, {, }, {-, }, {, }},
{{, }, {, -}, {, }, {-, }},
{{-, }, {, }, {, -}, {, }},
{{, }, {-, }, {, }, {, -}}
};
int dp[][][];
int dp2[][][];
int ans[][][];
char maze[][];
int sx, sy, ex, ey;
int n, m, P; bool ok(int nx, int ny, int np)
{
if (nx < || nx >= n || ny < || ny >= m) return false;
if (maze[nx][ny] == '*' || dp[nx][ny][np] != -) return false; return true;
} void BFS(void)
{
int x, y, nx, ny, p, np;
queue<int> q;
q.push (sx); q.push (sy); q.push (); while (!q.empty ())
{
x = q.front (); q.pop ();
y = q.front (); q.pop ();
p = q.front (); q.pop (); if (x == ex && y == ey && ans[x][y][p] == -)
ans[x][y][p] = dp[x][y][p]; nx = x + dir[dp[x][y][p]/P%][p][];
ny = y + dir[dp[x][y][p]/P%][p][];
if (ok (nx, ny, p)) //move robot, not move dir
{
dp[nx][ny][p] = dp[x][y][p] + ;
q.push (nx); q.push (ny); q.push (p);
} np = p + ;
if (np > ) np = ;
if (ok (x, y, np)) //not move robot, move dir to right
{
dp[x][y][np] = dp[x][y][p] + ;
q.push (x); q.push (y); q.push (np);
} np = p - ;
if (np < ) np = ;
if (ok (x, y, np)) //not move robot, move dir to left
{
dp[x][y][np] = dp[x][y][p] + ;
q.push (x); q.push (y); q.push (np);
} if (dp[x][y][p] <= ) //not move
{
dp[x][y][p]++;
q.push (x); q.push (y); q.push (p);
}
} return ;
} int main(void) //ZOJ 3865 Superbot
{
//freopen ("F.in", "r", stdin); int t;
scanf ("%d", &t);
while (t--)
{
memset (dp, -, sizeof (dp));
memset (ans, -, sizeof (ans)); scanf ("%d%d%d", &n, &m, &P); for (int i=; i<n; ++i) scanf ("%s", &maze[i]);
for (int i=; i<n; ++i)
{
for (int j=; j<m; ++j)
{
if (maze[i][j] == '@') sx = i, sy = j;
else if (maze[i][j] == '$') ex = i, ey = j;
}
} dp[sx][sy][] = ;
BFS (); int mn = INF;
for (int i=; i<; ++i)
{
if (ans[ex][ey][i] == -) continue;
mn = min (mn, ans[ex][ey][i]);
} if (mn == INF) printf ("YouBadbad\n");
else printf ("%d\n", mn);
} return ;
}