【NOIP2013】华容道

题面

https://www.luogu.org/problem/P1979

题解

$bfs$

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int dx[]={1,0,-1,0},dy[]={0,1,0,-1};
int f[35][35][35][35],map[35][35];
int n,m,q;

inline int abs(int x){
  if (x>0) return x;else return -x;
}

struct node{
  int tox,toy,emx,emy,step;
} que[1000000];

inline bool can(int cur,int x,int y,int x2,int y2){
  if (x2==x && y2==y) return false;
  if (x2>=1 && x2<=n && y2>=1 && y2<=m && map[x2][y2] && f[x][y][x2][y2]<cur) return true; else return false;
}

int main(){
  register int i,j;
  register int sx,sy,tx,ty,ex,ey,tail,head,ex0,ey0,x0,y0;
  scanf("%d %d %d",&n,&m,&q);
  for (i=1;i<=n;i++)
    for (j=1;j<=m;j++) scanf("%d",&map[i][j]);
  for (i=1;i<=q;i++) {
    scanf("%d %d %d %d %d %d",&ex,&ey,&sx,&sy,&tx,&ty);
    if (sx==tx && sy==ty) {
      puts("0");
      goto L1;
    }
    que[1]=(node){sx,sy,ex,ey,0};
    f[sx][sy][ex][ey]=i;
    tail=1; head=1;
    while (head<=tail) {
      ex0=que[head].emx; ey0=que[head].emy;
      x0=que[head].tox;   y0=que[head].toy;
      if (abs(ex0-x0)+abs(ey0-y0)==1 && f[ex0][ey0][x0][y0]<i)  {
        if (ex0==tx && ey0==ty) {
          printf("%d\n",que[head].step+1);
          goto L1;
        }
        que[++tail]=(node){ex0,ey0,x0,y0,que[head].step+1};
        f[ex0][ey0][x0][y0]=i;
      }
      for (j=0;j<=3;j++) if (can(i,x0,y0,ex0+dx[j],ey0+dy[j])) {
        que[++tail]=(node){x0,y0,ex0+dx[j],ey0+dy[j],que[head].step+1};
        f[x0][y0][ex0+dx[j]][ey0+dy[j]]=i;
      }
      head++;
    }
    puts("-1");
    L1:;
  }
}

猜你喜欢

转载自www.cnblogs.com/shxnb666/p/11277911.html