#include <iostream>
#include <cstdint>
#include <vector>
#include <algorithm>

using namespace std;
#define endl "\n"
#define ll long long


void popuniMatricu(const uint32_t& istart, const uint32_t& jstart, const uint32_t& N, const uint32_t& M, vector<vector<uint_fast64_t>>& navijaci, const uint32_t& x, const uint32_t& y)
{
    for (uint32_t i = istart; i < N; i++) {
        for (uint32_t j = jstart; j < M; j++) {
            if (navijaci[i][j] == navijaci[x][y]) {
                continue;
            }
            navijaci[i][j] += min(navijaci[i][j - 1], navijaci[i - 1][j]);
        }
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    uint32_t N, M,Q;
    cin >> N >> M;
    vector<vector<uint_fast64_t>> navijaci(N);
    vector<vector<uint_fast64_t>> startnavijaci;
    vector<uint32_t> X;
    vector<uint32_t> Y;
    for (uint32_t i = 0; i < N; i++) {
        navijaci[i].resize(M);
        for (uint32_t j = 0; j < M; j++) {
            cin >> navijaci[i][j];
        }
    }
    copy(navijaci.begin(), navijaci.end(), back_inserter(startnavijaci));
    cin >> Q;
    for (uint32_t i = 0; i < Q; i++) {
        uint32_t x, y;
        cin >> x >> y;
        X.push_back(x - 1);
        Y.push_back(y - 1);
 
    }


    for (uint32_t k = 0; k < Q; k++) {

        uint32_t x = X[k]; uint32_t y = Y[k];
        navijaci[x][y] = UINT32_MAX;

        for (uint32_t i = 1; i < N; i++) {
            if (navijaci[i - 1][0] == navijaci[x][y]) {
                navijaci[i][0] = navijaci[x][y];
                continue;
            }
            navijaci[i][0] += navijaci[i - 1][0];
        }
        for (uint32_t j = 1; j < M; j++) {
            if (navijaci[0][j - 1] == navijaci[x][y]) {
                navijaci[0][j] = navijaci[x][y];
                continue;
            }
            navijaci[0][j] += navijaci[0][j - 1];
        }
        popuniMatricu(1, 1, N, M, navijaci, x, y);
        cout << navijaci[N - 1][M - 1] << endl;
        navijaci.clear();
        copy(startnavijaci.begin(), startnavijaci.end(), back_inserter(navijaci));
    }


    return 0;
}