#include using namespace std; #include using namespace atcoder; using mint=modint998244353; //1000000007; using ll=long long; using pp=pair; #define sr string #define vc vector #define fi first #define se second #define rep(i,n) for(int i=0;i<(int)n;i++) #define pb push_back #define all(v) v.begin(),v.end() #define pque priority_queue #define bpc(a) __builtin_popcount(a) int x[]={0,-1,0,1}; int y[]={1,0,-1,0}; int main(){ int h,w;cin>>h>>w; vc v(h,vc(w)); rep(i,h)rep(j,w)cin>>v[i][j]; int q;cin>>q; int n=h*w; vc>s(n); dsu d(n); auto f=[&](int i,int j)->int{return i*w+j;}; auto r=[&](int a)->pp{return {a/w,a%w};}; rep(z,q){ int i,j,ni,nj;cin>>i>>j>>ni>>nj; ni--,nj--,i--,j--; s[f(i,j)].insert(z); s[f(ni,nj)].insert(z); } vc rv(n+1,vc(0)); rep(i,h)rep(j,w)rv[v[i][j]].pb(f(i,j)); vcans(q); vc bo(h,vc(w,0)); rep(now,n+1){ auto merge=[&](int a,int b)->void{ a=d.leader(a); b=d.leader(b); if(a==b)return; if(s[a].size()>s[b].size())swap(a,b); for(auto au:s[a]){ if(s[b].count(au)){ s[b].erase(au); ans[au]=now; continue; } s[b].insert(au); } s[a].clear(); d.merge(a,b); if(d.leader(a)==a)swap(s[a],s[b]); }; for(auto a:rv[now]){ auto [i,j]=r(a); bo[i][j]=1; rep(t,4){ int ni=i+x[t],nj=j+y[t]; if(ni<0||ni>=h||nj<0||nj>=w)continue; if(!bo[ni][nj])continue; merge(a,f(ni,nj)); } } } rep(i,q)cout<