#include <bits/stdc++.h>

void DST(std::vector<bool> &visited,std::vector<int> &distance,std::vector<std::vector<int>> &graph)
{
    int min,min_index;

    for(size_t i = 0; i < visited.size(); i++)
    {
        min=INT_MAX;

        for (size_t i = 0; i < visited.size(); i++)
        {
            if(!visited[i] && distance[i]<min)
            {
                min=distance[i];
                min_index=i;
            }
        }
        visited[min_index] = true;

        for(size_t j = 0; j < graph.size(); j++)
        {
            for(size_t k = 2; k < graph[j].size(); k++)
            {
            if(!visited[graph[j][k]]
            && graph[j][1]==min_index 
            && distance[min_index] != INT_MAX 
            && distance[min_index] + graph[j][0] < distance[graph[j][k]])
            {
                distance[graph[j][k]]=distance[min_index] + graph[j][0];
            }
            }
        }
    }
}

int main()
{
    std::vector<std::vector<int>> graph;
    int N,M;
    std::cin>>N>>M;
    std::vector<bool> visited(N*M,false);
    std::vector<int> distance(N*M,INT_MAX);
    std::vector<int> res;

    int a[N][M],ai[N][M];


    for (size_t i = 0; i < N; i++)
    {
        for (size_t j = 0; j < M; j++)
        {
            int tmp;
            
            std::cin>>tmp;
            a[i][j]=tmp;
        }
        
    }


    for (size_t i = 0; i < N; i++)
    {
        for (size_t j = 0; j < M; j++)
        {
            std::vector<int> tmp;
            tmp.push_back(a[i][j]);
            tmp.push_back(i*M+j);
            if(j-1<M)tmp.push_back(i*M+j-1);
            if(j+1<M)tmp.push_back(i*M+j+1);
            if(i-1<N)tmp.push_back((i-1)*M+j);
            if(i+1<N)tmp.push_back((i+1)*M+j);
            graph.push_back(tmp);
        }
        
    }
    int s,e,q,xi,yi;
    s=0; e=N*M-1;
    std::cin>>q;

    for (size_t i = 0; i < q; i++)
    {    
        std::cin>>xi>>yi;
        xi--;yi--;
        
        std::fill(visited.begin(), visited.end(), false);
        std::fill(distance.begin(), distance.end(), INT_MAX);
        distance[s]=0;
        visited[xi*M+yi]=true;
        DST(visited,distance,graph);
        res.push_back(distance[e]+a[N-1][M-1]);
    }

    for(int i:res)
    {
        std::cout<<i;
    }

    return 0;
}