#include <bits/stdc++.h>
using namespace std;
int n,m,a,b,q;
long long res;
vector < vector <long long >> v;
vector < vector <long long >> v2;
vector < vector <long long >> rez;
vector < vector <long long >> rez2;
int main(){
  cin>>n>>m;
  v.resize(n+3);
  v2.resize(n+3);
  rez.resize(n+3);
  rez2.resize(n+3);
  for(int i=0;i<n+3;i++)v[i].resize(m+5);
  for(int i=0;i<n+3;i++)v2[i].resize(m+5);
  for(int i=0;i<n+3;i++)rez[i].resize(m+5);
  for(int i=0;i<n+3;i++)rez2[i].resize(m+5);
  for(int i=0;i<=n+1;i++){
    for(int j=0;j<=m+1;j++){
        if(i==0 or i==n+1 or j==0 or j==m+1)v[i][j]=1e18;
        else cin>>v[i][j];
        v2[i][j]=v[i][j];
        if(i>=1 and i<=n and j>=1 and j<=m)rez2[i][j]=rez[i][j]=-v[i][j];
        else rez2[i][j]=rez[i][j]=v[i][j];
    }
  }
  if(n==2){
    for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)v[i][j]+=v[i][j-1];
    cin>>q;
    while(q--){
      scanf("%d %d",&a,&b);
      res=1e18;
      if(a==2)for(int i=b+1;i<=m;i++)res=min(res,v[1][i] + v[2][m] - v[2][i-1]);
      if(a==1)for(int i=1;i<b;i++)res=min(res,v[1][i] + v[2][m] - v[2][i-1]);
      cout<<res;
      printf("\n");
    }
    return 0;
  }
  for(int i=1;i<=n;i++)for(int j=1;j<=m;j++){if(i==1 and j==1)continue;v[i][j]+=min(v[i-1][j],v[i][j-1]);}
  for(int i=n;i>=1;i--)for(int j=m;j>=1;j--){if(i==n and j==m)continue;v2[i][j]+=min(v2[i+1][j],v2[i][j+1]);}
  for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)rez2[i][j]=rez[i][j]+=v[i][j]+v2[i][j];
  for(int i=1;i<=m;i++){
      long long mini=1e18;
      for(int j=1;j<=n;j++){
          mini=min(mini,rez[j][i]);
          rez[j][i]=mini;
      }
  }
  for(int i=1;i<=m;i++){
      long long mini=1e18;
      for(int j=n;j>=1;j--){
          mini=min(mini,rez2[j][i]);
          rez2[j][i]=mini;
      }
  }
  scanf("%d",&q);
  while(q--){
    scanf("%d %d",&a,&b);
    res=min(rez[a-1][b+1],rez2[a+1][b-1]);
    cout<<res;
    printf("\n");
  }

  return 0;
}
/*/
2 5
1 1 1 1 1
1 1 1 1 1
5


/*/