Program Problem3;

Type
   Locate=Array [1..2] of shortint;

var
   ADoc,BDoc:text;
   BigLoop,LoopX,LoopY:integer;
   Floor:Array [1..40] of String[40];
   R,C,TempA,Counter:integer;
   Position:Locate;
   TempB:char;

Function val(Thing1:Char):integer;
    var TempC:integer;
    Begin
    TempC:=ord(Thing1);
    Val:=TempC-48;
    End;

Procedure LocalCheck(Place:Locate;var Counter:integer);
   var
      Flag:Boolean;
   Begin
      Flag:=False;
      If Floor[Place[1],Place[2]]='.' then
         Begin
         Counter:=Counter+1;
         Flag:=True;
         End;
      If Flag=True then
         Begin
         If (Place[1]-1<>0) then
            Begin
            Place[1]:=Place[1]+1;
            LocalCheck(Place,Counter);
            Place[1]:=Place[1]-1;
            End;
         If Place[1]+1<>C then
            Begin
            Place[1]:=Place[1]-1;
            LocalCheck(Place,Counter);
            Place[1]:=Place[1]+1;
            End;
         If Place[2]-1<>0 then
            Begin
            Place[2]:=Place[2]+1;
            LocalCheck(Place,Counter);
            Place[2]:=Place[2]-1;
            End;
         If Place[2]<>R then
            Begin
            Place[2]:=Place[2]-1;
            LocalCheck(Place,Counter);
            Place[2]:=Place[2]+1;
            End;
         End;
      End;

Begin
   Assign(ADoc,'DATA3.txt');
   Assign(BDoc,'OUT3.txt');

   Reset(ADoc);
   Rewrite(BDoc);

   Readln(ADoc,R);
   Readln(ADoc,C);

   For LoopX:=1 to 40 do
      Floor[LoopX]:='';
   For BigLoop:=1 to 5 do
      Begin
         For LoopY:=1 to R do
             Readln(ADoc,Floor[LoopY]);
         For LoopY:=1 to C do
             For LoopX:=1 to R do
                 begin
                 TempB:=Floor[LoopX,LoopY];
                 TempA:=val(TempB);
                 If TempA=BigLoop then
                    Begin
                    Position[1]:=LoopX;
                    Position[2]:=LoopY;
                    End;
                 End;
         Counter:=1;
         LocalCheck(Position,Counter);
         Writeln(BDoc,Counter);
      End;
   Close(BDoc);
End.

