#include<stdio.h>
#include<iostream>
#include<math.h>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
#define ll long long
vector<vector<unsigned ll>> a;
//a[x][y]
// n - broj redova, m - broj kolona
unsigned ll mins(unsigned ll a, unsigned ll b) {
	if (a > b)return b;
	return a;
}
unsigned ll idk(ll n, ll m, ll x, ll y, ll bx, ll by) {
	if (x == n - 1 && y == m - 1) return a[n - 1][m - 1];
	if (bx == n - 1 && x == bx - 1 && y <= by)return a[x][y] + idk(n, m, x + 1, y, bx, by);
	if (by == m - 1 && x == by - 1 && x <= bx)return a[x][y] + idk(n, m, x, y + 1, bx, by);
	if (x + 1 == n || (x + 1 == bx && y == by))return a[x][y] + idk(n, m, x, y + 1, bx, by);
	if (y + 1 == n || (y + 1 == by && x == bx))return a[x][y] + idk(n, m, x + 1, y, bx, by);
	else {
		return a[x][y] + min(idk(n, m, x + 1, y, bx, by), idk(n, m, x, y + 1, bx, by));
	}
}
int main() {
	ll n, m;
	cin >> n >> m;
	int i, j;
	for (i = 0; i < n; i++) {
		vector<unsigned ll> ax;
		for (j = 0; j < m; j++) {
			unsigned ll tr; cin >> tr;
			ax.push_back(tr);
		}
		a.push_back(ax);
	}
	int q;
	cin >> q;
	int b[500000][2];
	unsigned ll c[500000];
	for (i = 0; i < q; i++) {
		cin >> b[i][0] >> b[i][1];
		c[i] = idk(n, m, 0, 0, b[i][0], b[i][1]);
	}
	for (i = 0; i < q; i++) {
		cout << c[i] << "\n";
	}
}