洛谷 P1519 穿越栅栏 Overfencing

将两个出口找出来,然后跑两遍BFS,每个点都维护一个距离的最小值。

注意:

  • 从出口往里跳的时候只能挑一格。

  • 从别的格子跳往其他格子的时候只能跳两格

  • 跳两格的时候还必须判断中间隔过去的一格是不是空格

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    typedef pair<int ,int > P;
    #define INF 0x3f3f3f3f
    const int Max=10000+10;
    int dx[4]= {-1,0,1,0};
    int dy[4]= {0,1,0,-1};
    int rx[4]= {-2,0,2,0};
    int ry[4]= {0,2,0,-2};
    int w,h,num,t;
    struct node {
    	int xx,yy,sum;
    } st[2];
    int a[250][100];
    char m[250][100];
    bool vis[250][100];
    queue<node> q;
    void bfs(int x) {
    	memset(vis,0,sizeof vis);
    	while(!q.empty())
    		q.pop();
    	node temp,now;
    	temp.xx=st[x].xx,temp.yy=st[x].yy,temp.sum=0;
    	int txx=st[x].xx,tyy=st[x].yy;
    	vis[txx][tyy]=1;
    	q.push(temp);
    	while(!q.empty()) {
    		now=q.front();
    		a[now.xx][now.yy]=min(a[now.xx][now.yy],now.sum);
    		q.pop();
    		for(int i=0; i<4; i++) {
    			int tx=now.xx+rx[i],ty=now.yy+ry[i];//跳2格 
    			int ttx=now.xx+dx[i],tty=now.yy+dy[i];//跳1格 
    			if(!(now.xx==txx&&now.yy==tyy)&&!vis[tx][ty]&&m[tx][ty]==' '&&m[ttx][tty]==' '&&
    			        tx>0&&tx<=2*h+1&&ty>0&&ty<=2*w+1) {
    				vis[tx][ty]=1;
    				temp.xx=tx,temp.yy=ty,temp.sum=now.sum+1;
    				q.push(temp);
    			}
    			if((now.xx==txx&&now.yy==tyy)&&!vis[ttx][tty]&&m[ttx][tty]==' '&&ttx>0&&ttx<=2*h+1&&
    			        tty>0&&tty<=2*w+1) {
    				vis[ttx][tty]=1;
    				temp.xx=ttx,temp.yy=tty,temp.sum=now.sum+1;
    				q.push(temp);
    			}
    		}
    
    	}
    }
    int main() {
    	int sum=0;
    	num=0;
    	scanf("%d%d",&w,&h);
    	gets(m[0]);
    	for(int i=1; i<=2*h+1; i++) {
    		gets(m[i]+1);
    		for(int j=1; j<=2*w+1; j++)
    			if(j==1||j==2*w+1||i==1||i==2*h+1) {
    				if(m[i][j]==' ')
    				st[num].xx=i,st[num++].yy=j;
    			}
    	}
    	t=0;
    	memset(a,INF,sizeof a);
    	bfs(0);
    	bfs(1);
    	for(int i=1;i<=2*h+1;i++)
    	    for(int j=1;j<=2*w+1;j++)
    	       if(a[i][j]!=INF)
    	       t=max(t,a[i][j]);
    	printf("%d\n",t);
    	return 0;
    }
    
    

猜你喜欢

转载自blog.csdn.net/PinkAir/article/details/81869217