#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int najbolji(int b, int c, vector<vector<int>> a, int x, int y){
    int g = (a[0].size()-b != 1) ? najbolji(b+1, c, a, x, y) : 2*pow(10, 9);
    int h = (a.size()-c != 1) ? najbolji(b, c+1, a, x, y) : 2*pow(10, 9);

    if(a[0].size()-b == 1 && a.size()-c == 1) return a[a.size()-1][a[0].size()-1];
    else if((a[0].size()-b == 1 && b == x && c+1 == y) || (a.size()-c == 1 && b+1 == x && c == y)) return 2*pow(10, 9);
    else if(((b+1 != x || c != y) && g < h) || (b == x && c+1 == y) || a.size()-c == 1) return a[c][b] + g;
    else return a[c][b] + h;
}

int main() {
    int n, m, b; //dimenzije matrice i broj pitanja
    cin >> n >> m;
    vector<vector<int>> a(n, vector<int> (m)); //lista s navijacima

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

    cin >> b;

    for(int i = 0; i < b; i++){
        int x, y;
        cin >> x >> y;

        cout << najbolji(0, 0, a, y-1, x-1) << endl;
    }
}