#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int N, M, Q, temp_i, temp_j;
bool temp_b = false;
void reset();
void f(int x, int y, int i);
vector<vector<int>> g;
vector<vector<bool>> visited;
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> q;
vector<int> s;
vector <int> temp_v;
vector <bool> temp_v1;


void f(int x, int y, int i)
{
	q.push({ g[1][1], {1, 1} });
	while (!q.empty()){
		int x1 = q.top().second.first, y1 = q.top().second.second, val1 = q.top().first;
		if (x1 <= N && y1 <= M && (x1 != x || y1 != y) && !visited[x1][y1]) {
			if (x1 == N && y1 == M) {
				s.push_back(val1);
				if(i != Q) reset();
				return;
			}
			visited[x1][y1] = true;
			q.pop();
			if(x1 < N) q.push({ val1 + g[x1 + 1][y1], {x1 + 1, y1} });
			if(y1 < M) q.push({ val1 + g[x1][y1 + 1], {x1, y1 + 1} });
		}
		else q.pop();
	}
}

void reset()
{
	visited.clear();
	for (int i = 0; i <= N; i++)
		for (int j = 1; j <= M; j++)
			visited.push_back(temp_v1);
	while (!q.empty())
		q.pop();
}

int main()
{
	temp_v.push_back(0);
	g.push_back(temp_v);
	s.push_back(0);
	cin >> N >> M;
	for (int j = 0; j <= M; j++){
		temp_v1.push_back(false);
	}
	visited.push_back(temp_v1);
	for (int i = 1; i <= N; i++) {
		for (int j = 1; j <= M; j++) {
			cin >> temp_i;
			temp_v.push_back(temp_i);
			visited.push_back(temp_v1);
		}
		g.push_back(temp_v);
		temp_v.clear();
		temp_v.push_back(0);
	}
	cin >> Q;
	for (int i = 1; i <= Q; i++) {
		cin >> temp_i >> temp_j;
		f(temp_i, temp_j, i);
	}
	for (int i = 1; i < s.size(); i++)
		cout << s[i] << "\n";
}