#include <bits/stdc++.h>
#define ll long long

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

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

    vector<vector<int>> a(n, vector<int> (m));

    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cin >> a[i][j];
        }
    }

    int q;
    cin >> q;
    while(q--) {
        vector<vector<int>> dp(n, vector<int> (m, 0));

        dp[0][0] = a[0][0];

        int x, y;
        cin >> x >> y;
        x--; y--;

        for(int i=1; i<n; i++) {
            if(i == x && y == 0) break;
            dp[i][0] = dp[i-1][0] + a[i][0];
        }

        for(int i=1; i<m; i++) {
            if(i == y && x == 0) break;
            dp[0][i] = dp[0][i-1] + a[0][i];
        }

        for(int i=1; i<n; i++) {
            for(int j=1; j<m; j++) {

                if(i == x && j == y) continue;

                if(dp[i-1][j] > 0 && dp[i][j-1] > 0)
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + a[i][j];
                else
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + a[i][j];
            }
        }

        cout << dp[n-1][m-1] << endl;
    }

    return 0;
}