program Project2out;


type
  tpoint = record
    x,y:longint;
  end;

var
  t,ti,r,s,k,i,j,l:longint;
  map,map2:array of array of longint;
  str:array of Tpoint;
  tmp:char;

begin

  readln(t);
  for ti:=1 to t do
  begin
    readln(r,s);
    setlength(map,r,s);setlength(map2,r,s);
    for i:=0 to r-1 do
    begin
      for j:=0 to s-1 do
      begin
        read(tmp);
        map[i,j]:=ord(tmp);
      end;
      readln;
    end;
    readln(k);
    setlength(str,k);
    for i:=0 to k-1 do readln(str[i].x,str[i].y);
    for i:=0 to r-1 do
      for j:=0 to s-1 do
      begin
        map2[i,j]:=map[i,j];
      for l:=0 to k-1 do
        if(i+str[l].x > -1)and
          (i+str[l].x < r)and
          (j+str[l].y > -1)and
          (j+str[l].y < s)then
          if map2[i,j] > map[i+str[l].x,j+str[l].y] then map2[i,j]:=map[i+str[l].x,j+str[l].y];
      end;
    //writeln(length(map[0]));
    for i:=0 to r-1 do
    begin
      for j:=0 to s-1 do write(chr(map2[i,j]));
      writeln;
    end;
  end;

end.