#include <bits/stdc++.h>

using namespace std;
typedef int Cvor;
typedef double Duzina;
typedef pair<Duzina, Cvor> Par;
typedef tuple<Duzina, Cvor, Cvor> Trojka;
const Duzina INF = numeric_limits<Duzina>::infinity();

int main()
{
    ios_base::sync_with_stdio(0);
    int n,m;
    cin >> n >> m;
    vector<vector<Par>> veze(n*m);
    bool pocetak = true;
    int pocetna_guzva = 0;
    vector<int> vektor;
    vector<vector<int>> matrica(n*m);
    for(int i = 0;i<n;i++){
        for(int j = 0;j<m;j++){
            int a;
            cin >> a;
            vektor.push_back(Duzina(a));
            matrica[i].push_back(a);
    }
}
int Q;
cin >> Q;
int bp = Q;
vector<pair<int,int>> a(Q);
vector<int> del;
for(int i = 0;i<Q;i++){
    cin >> a[i].first >> a[i].second;
    del.push_back(matrica[a[i].first-1][a[i].second-1]);
}
for(Cvor i = 0;i<vektor.size()-1;i++){
    veze[i].emplace_back(vektor[i],i+1);
    if(i+m<n*m){
        veze[i].emplace_back(vektor[i+m],i+m);
    }
}
for(int k = 0;k<bp;k++){
    int start = 0;
    int cilj = (n*m)-1;
    vector<Duzina> duzinaPuta(n*m, INF);
  vector<bool> resen(n*m, false);
  resen[(a[k].first-1)*m+a[k].second-1]=true;
  vector<Cvor> roditelji(n*m, -1);
  duzinaPuta[start] = 0;
  priority_queue<Trojka, vector<Trojka>, greater<Trojka>> pq;
  pq.emplace(0, start, -1);
  bool izadji = true;
  while (!pq.empty()) {
    Cvor cvorMin, roditelj; Duzina minDuzina;
    tie(minDuzina, cvorMin, roditelj) = pq.top(); pq.pop();
    if (resen[cvorMin])
      continue;
    resen[cvorMin] = true;
    roditelji[cvorMin] = roditelj;
    if (cvorMin == cilj)
      break;
    for (const auto& p : veze[cvorMin]) {
      Cvor cvor; Duzina duzina;
      tie(duzina, cvor) = p;
      if (!resen[cvor] && minDuzina + duzina < duzinaPuta[cvor]) {
        duzinaPuta[cvor] = minDuzina + duzina;
        pq.emplace(duzinaPuta[cvor], cvor, cvorMin);
      }
    }
  }
    stack<Cvor> put;
    put.push(cilj);
    while (roditelji[cilj] != -1) {
      cilj = roditelji[cilj];
      put.push(cilj);
    }
    long long S=0;
    while (!put.empty()) {
      S+=vektor[put.top()];
      put.pop();
    }
    cout << S;
    cout << endl;

}
    return 0;
  }