#include <cstdio>
#include <cstdlib>
#include <algorithm>
#define MAX 1000000
using namespace std;
typedef struct bud{
        long long kol,red,vre;
        }bud;
bud vtp[MAX];
long long n,i,z;
long long q,neb,r,c,a,b,j;
int cmp(bud a, bud b){
    return a.vre > b.vre;
}
long long maxx;
int main(){
    freopen("pentranje.in","r",stdin);
    freopen("pentranje.out","w",stdout);
    scanf("%I64d",&n);
    for(i = 0; i < n * n; i++){
                scanf("%I64d",&z);
                vtp[i].vre = z;
                vtp[i].kol = i % n;
                vtp[i].red = i / n;
                }
    sort(vtp,vtp+(n*n),cmp);
 scanf("%I64d",&q);
 if(q % 2 == 1){
 for(j = 0; j < q; j++){
      maxx = 0;
      i = 0;
      scanf("%I64d %I64d %I64d",&neb,&r,&c);
                  while (!((vtp[i].kol == c)&&(vtp[i].red = r)))i++;
                                  while(vtp[i].vre == vtp[i+1].vre) i++;
                                  i++;
                                  while(i<n*n){
                                               a = vtp[i].red - r;
                                               b = vtp[i].kol - c;
                                               if(a + b > maxx){

                                                        maxx = abs(a) + abs(b);
                                                        }// if
                                                        i++;
                                                        }//while
               if(maxx == 0) printf("-1\n");
               else printf("%I64d\n",maxx);
      }
      }                               
    return 0;
}
