#include <bits/stdc++.h>

using namespace std;

vector<vector<long long>> a;
vector<vector<long long>> sum;

vector<long long> sol;

long long path(int i, int j, int iobs, int jobs)
{
    double p = sum[iobs][jobs];
    sum[iobs][jobs] = LONG_MAX;


        if(i - 1 >= 0 && j - 1 >= 0)
        {
            if(sum[i - 1][j] == -1)
                sum[i - 1][j] = path(i - 1, j, iobs, jobs);
            if(sum[i][j - 1] == -1)
                sum[i][j - 1] = path(i, j - 1, iobs, jobs);

            sum[i][j] = min(sum[i][j - 1], sum[i - 1][j]) + a[i][j];

            sum[iobs][jobs] = p;
            return sum[i][j];
        }
        else if(i - 1 >= 0)
        {
            if(sum[i - 1][j] == -1)
                sum[i - 1][j] = path(i - 1, j, iobs, jobs);

            sum[i][j] = sum[i - 1][j] + a[i][j];


            sum[iobs][jobs] = p;
            return sum[i][j];
        }
        else if(j - 1 >= 0)
        {
            if(sum[i][j - 1] == -1)
                sum[i][j - 1] = path(i, j - 1, iobs, jobs);

            sum[i][j] = sum[i][j - 1] + a[i][j];

            sum[iobs][jobs] = p;
            return sum[i][j];
        }
        else
        {
            sum[iobs][jobs] = p;
            return a[i][j];
        }
}

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

    int n;
    int m;

    cin >> n;
    cin >> m;

    for(int i = 0; i < n; i++)
    {
        vector<long long> v;

        a.push_back(v);
        sum.push_back(v);

        for(int j = 0; j < m; j++)
        {
            sum[i].push_back(-1);

            long long x;
            cin >> x;
            a[i].push_back(x);
        }
    }

    int q;
    cin >> q;

    for(int i = 0; i < q; i++)
    {
        int io;
        int jo;

        cin >> io;
        cin >> jo;

        sol.push_back(path(n - 1, m - 1, io - 1, jo - 1));

        for(int k = 0; k < n; k++)
        {
            for(int l = 0; l < m; l++)
            {
                sum[k][l] = -1;
            }
        }
    }

    for(int i = 0; i < q; i++)
    {
        cout << sol[i] << '\n';
    }


    return 0;
}