1. 程式人生 > >造人

造人

在這裡插入圖片描述
在這裡插入圖片描述
這題首先要求是迴文的,bfs就能起到構造指令的作用,構造完後跑一邊最短路徑,就完美結束了

#include<bits/stdc++.h>
using namespace std;
const int dx[4]={0,0,1,-1};
const int dy[4]={1,-1,0,0};
int T,n,m,A[55][55][55][55],p[55][55],dis[55][55],stx,sty,enx,eny;
bool flag[55][55];
queue<int>qx1,qy1,qx2,qy2;
inline int read()
{
 char
c=getchar(); while(c!='#'&&c!='.'&&c!='F'&&c!='R') c=getchar(); if(c=='F') return 12345678; if(c=='R') return 87654321; return c=='.'; } void bfs(int a,int b,int c,int d) { memset(flag,0,sizeof(flag)); while(!qx1.empty()) { qx1.pop(); qx2.pop(); qy1.pop(); qy2.
pop(); } qx1.push(a); qy1.push(b); qx2.push(c); qy2.push(d); flag[a][b]=flag[c][d]=1; while(!qx1.empty()) { int xx1=qx1.front(); int yy1=qy1.front(); int xx2=qx2.front(); int yy2=qy2.front(); qx1.pop(); qx2.pop(); qy1.pop(); qy2.pop(); A[xx1][yy1][xx2][yy2]=A[xx2][yy2][xx1]
[yy1]=1; for(int k=0;k<4;k++) { int x=xx1+dx[k]; int y=yy1+dy[k]; int xx=xx2+dx[k^1]; int yy=yy2+dy[k^1]; if(flag[x][y]||flag[xx][yy]) continue; if(x>0&&x<=n&&y>0&&y<=m&&xx>0&&xx<=n&&yy>0&&yy<=m&&p[x][y]&&p[xx][yy]) { qx1.push(x); qy1.push(y); qx2.push(xx); qy2.push(yy); flag[x][y]=1; flag[xx][yy]=1; } } } } void SPFA(int x,int y) { memset(dis,0x3f,sizeof(dis)); dis[x][y]=0; while(!qx1.empty()) { qx1.pop(); qx2.pop(); qy1.pop(); qy2.pop(); } qx1.push(x); qy1.push(y); while(!qx1.empty()) { int x=qx1.front(); int y=qy1.front(); qx1.pop(); qy1.pop(); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(A[x][y][i][j]&&dis[x][y]+1<dis[i][j]) { dis[i][j]=dis[x][y]+1; qx1.push(i); qy1.push(j); } } } } } int main() { scanf("%d",&T); while(T--) { memset(A,0,sizeof(A)); memset(p,0,sizeof(p)); scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) p[i][j]=read(); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(p[i][j]) bfs(i,j,i,j); if(p[i][j]&&p[i][j+1]) bfs(i,j,i,j+1); if(p[i][j]&&p[i+1][j]) bfs(i,j,i+1,j); if(p[i][j]==12345678) enx=i,eny=j; if(p[i][j]==87654321) stx=i,sty=j; } } SPFA(stx,sty); if(dis[enx][eny]>10000000) printf("-1\n"); else printf("%d\n",dis[enx][eny]); } return 0; }

來源:zr