const zoux:array[1..4] of longint = (1,-1,0,0);
zouy:array[1..4] of longint = (0,0,1,-1);
var map:array[1..200,1..200] of longint;
stone:array[0..4] of longint; //stone de num
gate:array[1..10] of record
x,y:longint;
end;
line:array[1..100000000] of record
x,y,pre:longint;
end;
i,g,h,j,k,l,t,r,c,prinx,priny,afx,afy,gatenum,x,y,head,tail,baoshi,time:longint;
ex:boolean;
procedure readmap;
var i,j:longint;
c1:char;
begin
for i:= 1 to r do
for j:= 1 to c do
begin
read(c1);
case c1 of
'E':begin
prinx:=i;
priny:=j;
map[prinx,priny]:=1; //princess
end;
'S':begin
afx:=i; //hero
afy:=j;
end;
'$':begin
map[i,j]:=3; //gate
inc(gatenum);
gate[gatenum].x:=i;
gate[gatenum].y:=j;
end;
'.':begin
map[i,j]:=4; //empty
end;
'#':begin
map[i,j]:=0; //ban
end;
'0':begin
map[i,j]:=5; //stone1
end;
'1':begin
map[i,j]:=6; //stone2
end;
'2':begin
map[i,j]:=7; //stone3
end;
'3':begin
map[i,j]:=8; //stone4
end;
'4':begin
map[i,j]:=9; //stone5
end;
end;
end;
end;
procedure myget(head,baoshi:longint);
var i,j:longint;
begin
ex:=false;
if line[head].pre<>0 then
begin
if map[line[head].x,line[head].y]>4 then
begin
if stone[map[line[head].x,line[head].y]-5]=0 then
begin
inc(baoshi);
inc(stone[map[line[head].x,line[head].y]-5]);
end;
end;
if map[line[head].x,line[head].y]<>3 then
time:=time+1
else
time:=time;
myget(line[head].pre,baoshi)
end
else
begin
inc(time);
if map[line[head].x,line[head].y]>4 then
begin
if stone[map[line[head].x,line[head].y]-5]=0 then
begin
inc(baoshi);
inc(stone[map[line[head].x,line[head].y]-5]);
end;
end;
if baoshi>=k then
ex:=true;
end;
end;
Begin
assign(input,'003.txt');
reset(input);
readln(t);
l:=1;
repeat
gatenum:=1;
readln(r,c,k);
readmap;
head:=0;
tail:=1;
line[tail].x:=afx;
line[tail].y:=afy;
line[tail].pre:=0;
x:=afx;
y:=afy;
while tail<>head do
begin
inc(head);
for i:= 1 to 4 do
begin
x:=line[tail].x+zoux[i];
y:=line[tail].y+zouy[i];
if (x<1)or(x>r)or(y<1)or(y>c) then
continue;
if map[x,y]<>0 then
begin
inc(tail);
line[tail].x:=x;
line[tail].y:=y;
line[tail].pre:=head;
if map[x,y]=3 then
begin
for g:= 1 to gatenum+1 do
if g<=gatenum then
begin
x:=gate[g].x;
y:=gate[g].y;
line[tail].x:=x;
line[tail].y:=y;
line[tail].pre:=head;
inc(tail);
end;
end;
if (x=prinx)and(y=priny) then
begin
time:=0;
myget(head,0);
if ex=true then
begin
write(time);
end;
if ex=true then break;
end;
end;
end;
if ex=true then break;
end;
inc(l);
r:=0;
c:=0;
prinx:=0;
priny:=0;
afx:=0;
afy:=0;
gatenum:=0;
x:=0;
y:=0;
head:=0;
tail:=0;
baoshi:=0;
time:=0;
ex:=false;
until l=t+1;
readln;
readln;
End.