#include<iostream>
#include<limits>
#include<queue>
using namespace std;
const int beskonacno=1000000001;
int put[1002][1002];
int doha[1002][1002];
int beskonacna[1002][1002];
bool posecena[1002][1002];
bool fal[1002][1002];

int putanja(int i,int j){
int minimalni=put[i][j];
if(put[i-1][j]<minimalni)minimalni=put[i-1][j];
else if(put[i][j+1]<minimalni)minimalni=put[i][j+1];
else if(put[i][j-1]<minimalni)minimalni=put[i][j-1];
else if(put[i+1][j]<minimalni)minimalni=put[i+1][j];
return minimalni;
}
void resi(int n,int m,int x,int y){
queue<pair<int,int>> red;
red.push(make_pair(1,1));
while(put[n][m]==beskonacno){
    pair<int,int> p;
    p=red.front();
    red.pop();
    int k=p.first;
    int l=p.second;
    if((k==x&&l==y)||posecena[k][l])continue;
    put[k][l]=putanja(k,l)+doha[k][l];
    posecena[k][l]=true;
    cout<<k<<" "<<l<<" "<<put[k][l]<<" "<<endl;
    if(k+1<n+1)red.push(make_pair((k+1),l));
    if(l+1<m+1)red.push(make_pair(k,l+1));

}
cout<<put[n][m]<<endl;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m;
cin>>n>>m;
for(int i=0;i<n+2;i++){
    for(int j=0;j<m+2;j++){
        put[i][j]=beskonacno;
        beskonacna[i][j]=beskonacno;
        posecena[i][j]=false;
        fal[i][j]=false;
        if(i>0&&i<n+1&&j>0&&j<m+1){
            int x;
            cin>>x;
            doha[i][j]=x;
        }

    }
}
int q;
cin>>q;
for(int i=0;i<q;i++){
    memcpy(put,beskonacna,sizeof(beskonacna));
    memcpy(posecena,fal,sizeof(fal));
    put[1][1]=0;
    int x,y;
    cin>>x>>y;
    resi(n,m,x,y);
}
return 0;
}