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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
| #include<bits/stdc++.h> using namespace std; #define rep(i,l,r) for(int i=l;i<=r;++i) const int INF=0x3f3f3f3f; const int dx[]= {0,0,1,-1}; const int dy[]= {1,-1,0,0}; const int N=31*31*4; const int M=4*N; struct node { int x,y; } q[32*32*4]; int n,m,k; int dis[32][32]; int can[32][32];
int e,head[M],last[M],w[M],p[N]; bool vis[N]; int dist[N]; bool ok(int x,int y) { return x>=0 && x<n && y>=0 && y<m && can[x][y]; }
void bfs(int sx,int sy) { memset(dis,INF,sizeof(dis)); dis[sx][sy]=0; int l=0,r=0; q[r++]=node{sx,sy}; while(l!=r) { int x=q[l].x; int y=q[l].y; l++; rep(i,0,3) { int xx=x+dx[i]; int yy=y+dy[i]; if(ok(xx,yy) && dis[xx][yy]==INF) { dis[xx][yy]=dis[x][y]+1; q[r++]=node{xx,yy}; } } } } int calc(int x,int y,int k) { return x*m*4+y*4+k; } void add(int x,int y,int c) { head[++e]=y; w[e]=c; last[e]=p[x]; p[x]=e; } void init() { rep(i,0,n-1) rep(j,0,m-1) if(ok(i,j)) { rep(k,0,3) { int x=i+dx[k]; int y=j+dy[k]; if(!ok(x,y)) continue; can[i][j]=0; bfs(x,y); can[i][j]=1; rep(h,0,3) if(h!=k) { int xx=i+dx[h]; int yy=j+dy[h]; if(ok(xx,yy) && dis[xx][yy]!=INF) add(calc(i,j,k),calc(i,j,h),dis[xx][yy]); } add(calc(i,j,k),calc(x,y,k^1),1); } } } void spfa(int sx,int sy) { queue<int> q; memset(vis,0,sizeof(vis)); memset(dist,INF,sizeof(dist)); rep(i,0,3) if(ok(sx+dx[i],sy+dy[i]) && dis[sx+dx[i]][sy+dy[i]]!=INF) { int now=calc(sx,sy,i); dist[now]=dis[sx+dx[i]][sy+dy[i]]; vis[now]=true; q.push(now); } while(!q.empty()) { int x=q.front(); q.pop(); vis[x]=false; for(int j=p[x]; j; j=last[j]) { int y=head[j]; if(dist[y]>dist[x]+w[j]) { dist[y]=dist[x]+w[j]; if(!vis[y]) { vis[y]=true; q.push(y); } } } } } int work(int x,int y,int sx,int sy,int tx,int ty) { if(sx==tx && sy==ty) return 0; can[sx][sy]=0; bfs(x,y); can[sx][sy]=1; spfa(sx,sy); int ans=INF; rep(i,0,3) ans=min(ans,dist[calc(tx,ty,i)]); if(ans==INF) ans=-1; return ans; }
int main() { scanf("%d%d%d",&n,&m,&k); rep(i,0,n-1) rep(j,0,m-1) scanf("%d",&can[i][j]); init(); while(k--) { int x,y,sx,sy,tx,ty; scanf("%d%d%d%d%d%d",&x,&y,&sx,&sy,&tx,&ty); --x;--y;--sx;--sy;--tx;--ty; printf("%d\n",work(x,y,sx,sy,tx,ty)); } }
|