P3395 路障(洛谷)

题目描述:

传送门

 

//题解:实质上就是一个bfs的简单变体,只需要在判断路障的时候加上步数与路障安放时间的判断即可,如果题目要用dfs解决的话则需要用递归层数和路障安放时间进行判断
注意题目:是每次B走完一步后  才安放路障  如果步数小于等于安放时间  那么代表当前点是可以访问的
 
代码:
#include<iostream>
#include<queue>
#include<algorithm>
#include<string.h>
using namespace std;

const int maxn=1000+10;
int color[maxn][maxn]={0};      //标志
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
int n;

typedef struct nod{
    int flag;       //是否有障碍的标志
    int time;       //代表障碍放置时间
}N;

typedef struct node{
    int x;
    int y;
    int step;           //代表从起始点到当前点的步数
}NN;
N o[maxn][maxn];      //存储障碍  注意障碍是实时安置的

bool bfs(int x,int y){
    queue<NN> que;
    NN a;
    a.x=x;
    a.y=y;
    a.step=0;
    color[x][y]=1;
    que.push(a);

    while(!que.empty()){
        NN temp=que.front();
        que.pop();

        // cout<<temp.x<<" "<<temp.y<<endl;
        if(temp.x==n&&temp.y==n)        return true;
        int tx;
        int ty;
        for(int i=0;i<4;i++){
            tx=temp.x+dx[i];
            ty=temp.y+dy[i];

            if(o[tx][ty].flag==1){      //代表会有路障
                if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&color[tx][ty]==0&&(temp.step+1)<=o[tx][ty].time){
                    color[tx][ty]=1;
                    NN te;
                    te.x=tx;
                    te.y=ty;
                    te.step=temp.step+1;
                    que.push(te);
                }
            }else{
                if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&color[tx][ty]==0){
                    color[tx][ty]=1;
                    NN te;
                    te.x=tx;
                    te.y=ty;
                    te.step=temp.step+1;
                    que.push(te);
                }
            }
        }
    }
    return false;
}
int main(){
    int t=0;
    cin>>t;
    for(int i=1;i<=t;i++){
        n=0;  
        cin>>n;
 

        for(int j=0;j<=n;j++){
            for(int k=0;k<=n;k++){
                o[j][k].flag=0;
                o[j][k].time=0;
                color[j][k]=0;          //清0
            }
        }
        for(int j=1;j<=2*n-2;j++){
            int a,b;
            cin>>a>>b;
            o[a][b].flag=1;
            o[a][b].time=j;             //代表是第j秒才放置的
        }
        if(bfs(1,1)){
            cout<<"Yes"<<endl;
        }else cout<<"No"<<endl;
    }
    return 0;
}

 

 

posted @ 2020-10-09 21:06  neverstopcoding  阅读(267)  评论(0编辑  收藏  举报