1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include<bits/stdc++.h> using namespace std;
void read(int &x) { x=0;int f=1;char ch=getchar(); for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-f; for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';x*=f; }
void print(int x) { if(x<0) putchar('-'),x=-x; if(!x) return ;print(x/10),putchar(x%10+48); } void write(int x) {if(!x) putchar('0');else print(x);putchar('\n');}
#define lf double #define ll long long
#define pii pair<int,int > #define vec vector<int >
#define pb push_back #define mp make_pair #define fr first #define sc second
#define data asd09123jdf02i3h
#define FOR(i,l,r) for(int i=l,i##_r=r;i<=i##_r;i++)
const int maxn = 1e3+10; const int inf = 1e9; const lf eps = 1e-8; const int mod = 1e9+7;
int c[maxn][maxn],f[maxn][maxn][51],n,m,k;
const int dx[] = {0,0,0,1,-1}; const int dy[] = {0,1,-1,0,0};
int check(int x,int y) {return x>0&&x<=n&&y>0&&y<=m;}
vector<pii > w[41]; int vis[41];
int main() { read(n),read(m),read(k); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) read(c[i][j]),w[c[i][j]].pb(mp(i,j)); for(int x=1;x<=k;x++) { queue<pii > q; for(int i=1;i<=k;i++) vis[i]=0; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) if(c[i][j]==x) q.push(mp(i,j)); else f[i][j][x]=inf; while(!q.empty()) { int xx=q.front().fr,y=q.front().sc;q.pop(); if(!vis[c[xx][y]]) { vis[c[xx][y]]=1; for(auto t:w[c[xx][y]]) if(f[t.fr][t.sc][x]==inf) q.push(t),f[t.fr][t.sc][x]=f[xx][y][x]+1; } for(int u,v,i=1;i<=4;i++) if(check(u=xx+dx[i],v=y+dy[i])&&f[u][v][x]==inf) f[u][v][x]=f[xx][y][x]+1,q.push(mp(u,v)); } } int q;read(q); while(q--) { int a,b,c,d;read(a),read(b),read(c),read(d); int ans=abs(d-b)+abs(a-c); for(int i=1;i<=k;i++) ans=min(ans,f[a][b][i]+f[c][d][i]+1); write(ans); } return 0; }
|