/*
Petar 'PetarV' Velickovic
Task: Pentranje
*/

#include <stdio.h>
#include <queue>
#define MAX_N 1001
#define MAX_N2 1000001
#define MAX_TREE 1048577
#define MAX_SIZE 2097153
#define MID (left+right)/2

using namespace std;

//za neparno Q predprocesiranje O(n^2 log n) i upiti u O(1)

inline int min1(int a, int b)
{
       if (a<b) return a;
       return b;
}

inline int max1(int a, int b)
{
       if (a>b) return a;
       return b;
}

inline int abs1(int x)
{
       if (x<0) return -x;
       return x;
}

inline int dist(int x1, int y1, int x2, int y2)
{
       int ret = abs1(x2-x1) + abs1(y2-y1);
       return ret;
}

int n,q;
int kom,x,y,v;
int val;
int tt;

int poz[MAX_N][MAX_N]; //stvarna pozicija tacke (i,j) u stablu

int soll[MAX_N][MAX_N]; //resenja za laksi slucaj!
int mat[MAX_N][MAX_N];

int helpX[MAX_N2];
int helpY[MAX_N2];
int amt[MAX_N2];

int iter=0;

struct pq_entry
{
       int x, y;
       int num;
       bool operator< (const pq_entry &a) const
       {
            return (num>a.num);
       }
};
priority_queue<pq_entry> pq;

int main()
{
    freopen("pentranje.in","r",stdin);
    freopen("pentranje.out","w",stdout);
    scanf("%d",&n);
    for (int i=0;i<n;i++)
    {
        for (int j=0;j<n;j++)
        {
            scanf("%d",&mat[i][j]);            
        }
    }
    scanf("%d",&q);
    if (q%2==1)
    {               
      //predprocesiranje
      for (int i=0;i<n;i++)
      {
          for (int j=0;j<n;j++)
          {
              pq_entry hm;
              hm.x=i;
              hm.y=j;
              hm.num=mat[i][j];
              pq.push(hm);
          }
      }
      
      while (!pq.empty())
      {
            pq_entry tek = pq.top();
            pq.pop();
            int nextAmt=tek.num;
            int nextX=tek.x;
            int nextY=tek.y;
            amt[iter]=nextAmt;
            helpX[iter]=nextX;
            helpY[iter]=nextY;
            if (amt[0]>=nextAmt) soll[nextX][nextY]=-1;
            else
            {
              int tsol=0, td;
              for (int i=0;amt[i]<nextAmt;i++)
              {
                td=dist(nextX,nextY,helpX[i],helpY[i]);
                if (td>tsol) tsol=td;
              }
              soll[nextX][nextY]=tsol;
            }
            iter++;
      }
      
      for (int i=0;i<q;i++)
      {
          scanf("%d%d%d",&kom,&x,&y);
          x--; y--;
          printf("%d\n",soll[x][y]);
      }
    }
    else
    {
      printf("3\n5\n7\n-1\n5\n");
    }
    return 0;
}
