{
TASK:lab101
LANG:PASCAL
}

var
  t: array[0..11,0..11] of Byte;
  mp1,mp2: array[1..100] of Byte;
  x,y,a,b,k: array[1..32] of Byte;
  vis: array[1..10,1..10] of Boolean;
  n,m,p,i,j: Byte;
  x1,y1,x2,y2,x3,y3: Byte;
  min,ans: Byte;
  fl1,fl2: Boolean;



procedure visit;
var
  i,j: Byte;

begin
  for i:= 1 to n do
    for j:= 1 to m do
      vis[i,j]:= false;
end;


procedure mps(x,y,a1,b1,c,g: Byte);
var
  i: Byte;

begin
  c:=c+1;
  vis[x,y]:= true;

  if (a1=x3) and (b1=y3) then
  begin
    for i:= 1 to p do
      if (x=a[i]) and (y=b[i]) then
        k[i]:= g; 
  end;

  if (x<>a1) or (y<>b1) then
  begin
    if (t[x-1,y]=0) and (not vis[x-1,y]) then
      mps(x-1,y,a1,b1,c,g);
    if (t[x+1,y]=0) and (not vis[x+1,y]) then
      mps(x+1,y,a1,b1,c,g);
    if (t[x,y-1]=0) and (not vis[x,y-1]) then
      mps(x,y-1,a1,b1,c,g);
    if (t[x,y+1]=0) and (not vis[x,y+1]) then
      mps(x,y+1,a1,b1,c,g);
  end
  else
    if c<min then
      min:= c;  
end;


begin
  readln(n,m);
  for i:= 1 to n do
  begin
    for j:= 1 to m do
      read(t[i,j]);
    readln;
  end;
  readln(p);
  for i:= 1 to p do
    readln(x[i],y[i],a[i],b[i]);

  for i:= 1 to n do
  begin
    t[i,0]:= 1;
    t[i,m+1]:= 1;
  end;
  for i:= 1 to m do
  begin
    t[0,i]:= 1;
    t[n+1,i]:= 1;
  end;
  for i:= 1 to n do
    k[i]:= 0;

  readln(x1,y1); readln(x2,y2); readln(x3,y3);

  fl1:= false; fl2:= false;

if ((t[x3-1,y3]=1) and (t[x3+1,y3]=1) and (t[x3,y3-1]=1) and (t[x3,y3+1]=1)) then
begin
  writeln(0);
  fl1:= true;
  fl2:= true;
end;

if (fl1=false) and (fl2=false) then
begin
  min:= 200;
  visit;
  mps(x1,y1,x3,y3,1,1);
  mp1[p+1]:= min;
  min:= 200;
  visit;
  mps(x2,y2,x3,y3,1,2);
  mp2[P+1]:= min;  

  for i:= 1 to p do
  begin
    visit;
    min:= 200;
    mps(x1,y1,x[i],y[i],1,1);
    mp1[i]:= min;

    visit;
    min:= 200;
    mps(x2,y2,x[i],y[i],1,2);
    mp2[i]:= min;
  end;

  fl1:= false; min:= 200;
  for i:= 1 to p do
    if k[i]<>0 then
    begin
      fl1:= true;
      if k[i]=1 then
        if mp2[i]<min then
        begin
          min:= mp2[i];
          ans:= 2;
        end;
      
      if k[i]=2 then
        if mp1[i]<min then
        begin
          min:= mp1[i];
          ans:= 1;
        end;
    end;

  if fl1 then
    writeln(ans)
  else
  begin
    if mp1[p+1]<mp2[p+1] then
      writeln(1);
    if mp2[p+1]<mp1[p+1] then
      writeln(2);
    if (mp1[p+1]=200) and (mp2[p+1]=200) then
      writeln(0); 
  end;
end;  

end.