#include <bits/stdc++.h>

#define ll long long

using namespace std;

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n, m;
    cin >> n >> m;

    ll mat[n][m], to[n][m], from[n][m], pre_col[n][m], pre_row[n][m];

    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
            cin >> mat[i][j];
    
    // make to[][]
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            if(i == 0 && j == 0)
                to[i][j] = mat[i][j];
            else if(i == 0)
                to[i][j] = to[i][j - 1] + mat[i][j];
            else if(j == 0)
                to[i][j] = to[i - 1][j] + mat[i][j];
            else
                to[i][j] = min(to[i - 1][j], to[i][j - 1]) + mat[i][j];
        }
    }

    // make from[][]
    for(int i = n - 1; i >= 0; i--) {
        for(int j = m - 1; j >= 0; j--) {
            if(i == n - 1 && j == m - 1)
                from[i][j] = mat[i][j];
            else if(i == n - 1)
                from[i][j] = from[i][j + 1] + mat[i][j];
            else if(j == m - 1)
                from[i][j] = from[i + 1][j] + mat[i][j];
            else
                from[i][j] = min(from[i + 1][j], from[i][j + 1]) + mat[i][j];
        }
    }

    // make pre
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            ll dp = to[i][j] + from[i][j] - mat[i][j];

            pre_col[i][j] = (i ? min(pre_col[i - 1][j], dp) : dp);
            pre_row[i][j] = (j ? min(pre_row[i][j - 1], dp) : dp);
        }
    }

    int q;
    cin >> q;
    while(q--) {
        int x, y;
        cin >> x >> y;
        x--; y--;

        ll ans = LLONG_MAX;
        if(x > 0 && y < m - 1)
            ans = min(ans, pre_col[x - 1][y + 1]);
        if(x < n - 1 && y > 0)
            ans = min(ans, pre_row[x + 1][y - 1]);
        cout << ans << endl;
    }
    return 0;
}