using System;

namespace Marko_DjordjevicZadatak3
{
    class Program
    {
        static int N, M, Q;
        static int[][] a;
        static readonly int INF = int.MaxValue;

        static int NajmanjeFanova(int i, int j, int x, int y)
        {
            if (i < 1 || i > N || j < 1 || j > M)
                return INF - a[N][M];
            if (i == 1 && j == 1)
                return 1;
            if (i == x && j == y) return INF - a[N][M];
            return Math.Min(NajmanjeFanova(i - 1, j, x, y), NajmanjeFanova(i, j - 1, x, y)) + a[i][j];
        }

        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split(' ');
            N = int.Parse(s[0]);
            M = int.Parse(s[1]);
            a = new int[N + 1][];
            for (int i = 1; i <= N; i++)
            {
                s = Console.ReadLine().Split(' ');
                a[i] = new int[M + 1];
                for (int j = 1; j <= M; j++)
                {
                    a[i][j] = int.Parse(s[j - 1]);
                }
            }
            Q = int.Parse(Console.ReadLine());
            for (int q = 1; q <= Q; q++)
            {
                s = Console.ReadLine().Split(' ');
                int x = int.Parse(s[0]);
                int y = int.Parse(s[1]);
                Console.WriteLine(NajmanjeFanova(N, M, x, y));
            }
        }
    }
}