#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

vector<vector<ll> >a, gornja, donja;
ll xx[100010], yy[100010];

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    ll n, m;
    cin>>n>>m;
    for(int i=1; i<=n; i++)
    {
        vector<ll>pom, jd, dv;
        for(int j=1; j<=m; j++)
        {
            ll bb; cin>>bb;
            pom.push_back(bb);
            jd.push_back(0);
            dv.push_back(0);
        }
        a.push_back(pom);
        gornja.push_back(jd);
        donja.push_back(dv);
    }
    gornja[0][0]=a[0][0];
    for(int i=1; i<m; i++)
        gornja[0][i]=gornja[0][i-1]+a[0][i];
    for(int i=1; i<n; i++)
        gornja[i][0]=gornja[i-1][0]+a[i][0];

    for(int i=1; i<n; i++)
    {
        for(int j=1; j<m; j++)
        {
            gornja[i][j]=min(gornja[i-1][j], gornja[i][j-1])+a[i][j];
        }
    }

    donja[n-1][m-1]=a[n-1][m-1];
    for(int i=m-2; i>=0; i--)
        donja[n-1][i]=donja[n-1][i+1]+a[n-1][i];
    for(int i=n-2; i>=0; i--)
        donja[i][m-1]=donja[i+1][m-1]+a[i][m-1];

    for(int i=n-2; i>=0; i--)
    {
        for(int j=m-2; j>=0; j--)
        {
            donja[i][j]=min(donja[i+1][j], donja[i][j+1])+a[i][j];
        }
    }
    /*for(int i=0; i<n; i++)
        {for(int j=0; j<m; j++)cout<<donja[i][j]<<" ";
        cout<<endl;}*/
    ll q; cin>>q;
    for(int i=0; i<q; i++)cin>>xx[i]>>yy[i];
    for(int i=0; i<q; i++)
    {
        ll x=xx[i]-1, y=yy[i]-1;
        if(x==0 or y==m-1)cout<<gornja[x+1][y-1]+donja[x+1][y-1]-a[x+1][y-1]<<"\n";
        else if(y==0 or x==n-1)cout<<gornja[x-1][y+1]+donja[x-1][y+1]-a[x-1][y+1]<<"\n";
        else cout<<min(gornja[x-1][y+1]+donja[x-1][y+1]-a[x-1][y+1], gornja[x+1][y-1]+donja[x+1][y-1]-a[x+1][y-1])<<"\n";
    }
    return 0;
}