#define _USE_MATH_DEFINES
#include<iostream>
#include<sstream> 
#include<cmath>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<conio.h>
#include<numeric>
#include<map>
#include<set>
#include<stack>
#include<stdlib.h>  
#include<unordered_map>
#include<queue>
using namespace std;

#define int long long
#define forn(i,n) for(int i=0;i<n;i++)
#define prefix(i,n) for(int i=1;i<n;i++)


bool isValid(int i, int j, int M, int N) {
    return (i >= 0 && i < M&& j >= 0 && j < N);
}

void testPath(vector<int>&path, int last, int& ss, int& sz)
{
    int sum = 0;
    int br = 0;
    for (int i : path) {
        sum = sum + i;
        br++;
    }
    sum = sum + last;
    br++;
    if (br <= sz) {
        sz = br;
        if (sum <= ss) ss = sum;
    }
}

void findPaths(vector<vector<int>> &mat, vector<int> &path, int i, int j, int ty, int tx, int& ss, int& sz)
{
    if (mat.size() == 0) {
        return;
    }
    int M = mat.size();
    int N = mat[0].size();
    if (i == M - 1 && j == N - 1)
    {
        testPath(path, mat[i][j], ss, sz);
        return;
    }
    path.push_back(mat[i][j]);
    if (isValid(i, j + 1, M, N)) {
        if (mat[i][j + 1] != mat[ty][tx]) findPaths(mat, path, i, j + 1, ty, tx, ss, sz);
    }
    if (isValid(i + 1, j, M, N)) {
        if (mat[i + 1][j] != mat[ty][tx]) findPaths(mat, path, i + 1, j, ty, tx, ss, sz);
    }
    path.pop_back();
}

int32_t main() {
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int n, m;
    cin >> n >> m;
    vector<vector<int>> mat(n, vector<int>(m));
    vector<int> path;
    forn(i, n) forn(j, m) cin >> mat[i][j];

    int x = 0, y = 0;
    int q, tx, ty, ss = 1e10, sz = 1e10;
    cin >> q;
    while (q--) {
        cin >> ty >> tx;
        findPaths(mat, path, x, y, ty - 1, tx - 1, ss, sz);
        cout << ss << '\n';
        ss = 1e10;
        sz = 1e10;
    }

    return 0;
}