using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static int INF = 1000000000;

        static int[] dx = { -1, 0, 1, 0 }; 
        static int[] dy = { 0, 1, 0, -1 };

        static bool IsValid(int x, int y, int n, int m, int[,] distanca, int q, int p)
        {
            return x >= 0 && x < n && y >= 0 && y < m && distanca[x, y] == INF && !(x == p && y == q);
        }

        static int Bfs(int n , int m, int[,] matrica, int [,] distanca, int q, int p)
        {
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    distanca[i, j] = INF;
                }
            }

            distanca[0, 0] = 0;

            Queue<Tuple<int, int>> s = new Queue<Tuple<int, int>>();
            s.Enqueue(Tuple.Create(0, 0));

            while (s.Count > 0)
            {
                int x = s.Peek().Item1;
                int y = s.Peek().Item2;
                s.Dequeue();

                for (int i = 0; i < 4; i++)
                {
                    int novoX = x + dx[i];
                    int novoY = y + dy[i];
                    if (IsValid(novoX, novoY, n, m, distanca, q, p)) 
                    {
                        distanca[novoX, novoY] = distanca[x, y] + matrica[novoX, novoY];
                        s.Enqueue(Tuple.Create(novoX, novoY));
                    }
                }
            }
            return distanca[n - 1, m - 1];
        }


        static void Main(string[] args)
        {
            string[] a = Console.ReadLine().Split();

            int n, m, p, q;
            int[,] matrica;
            int[,] distanca;

            n = Convert.ToInt32(a[0]);
            m = Convert.ToInt32(a[1]);

            matrica = new int[n, m];
            distanca = new int[n, m];

            string[] b;
            for (int i = 0; i < n; i++)
            {
                b = Console.ReadLine().Split();
                for (int j = 0; j < m; j++)
                    matrica[i, j] = Convert.ToInt32(b[j]);
            }
            int pomoc = Convert.ToInt32(Console.ReadLine());
            int[] x = new int[pomoc];

            string[] c;

            for (int i = 0; i < pomoc; i++)
            {
                c = Console.ReadLine().Split();
                p = Convert.ToInt32(c[0]) - 1;
                q = Convert.ToInt32(c[1]) - 1;
                x[i] = Bfs(n, m, matrica, distanca, q, p) + matrica[0, 0];
            }
            for (int i = 0; i < x.Length; i++)
            {
                Console.WriteLine(x[i]);
            }
            Console.ReadKey();
        }
    }
}