路障(广度优先搜索)

题目描述:
B君站在一个n*n的棋盘上。最开始,B君站在(1,1)这个点,他要走到(n,n)这个点。
B君每秒可以向上下左右的某个方向移动一格,但是很不妙,C君打算阻止B君的计划。
每秒结束的时刻,C君会在(x,y)上摆一个路障。B君不能走在路障上。
B君拿到了C君准备在哪些点放置路障。所以现在你需要判断,B君能否成功走到(n,n)。
保证不会走到某处,然后被一个路障砸死。
输入输出格式
输入格式:
首先是一个正整数T,表示数据组数。
对于每一组数据:
第一行,一个正整数n。
接下来2n-2行,每行两个正整数x和y,意义是在那一秒结束后,(x,y)将被摆上路障。
输出格式:
对于每一组数据,输出Yes或No,回答B君能否走到(n,n)。
输入输出样例
输入样例#1:
2
2
1 1
2 2
5
3 3
3 2
3 1
1 2
1 3
1 4
1 5
2 2
输出样例#1:
Yes
Yes
说明
样例解释:
以下0表示能走,x表示不能走,B表示B君现在的位置。从左往右表示时间。
Case 1:
0 0 |0 0 |0 B (已经走到了)
B 0 |x B |x 0
Case 2:
0 0 0 0 0 |0 0 0 0 0 |0 0 0 0 0 |0 0 0 0 0
0 0 0 0 0 |0 0 0 0 0 |0 0 0 0 0 |0 0 0 0 0
0 0 0 0 0 |0 0 x 0 0 |0 0 x 0 0 |0 0 x 0 0
0 0 0 0 0 |0 0 0 0 0 |0 0 x 0 0 |0 0 x 0 0
B 0 0 0 0 |0 B 0 0 0 |0 0 B 0 0 |0 0 x B 0 ……(B君可以走到终点)
数据规模:
防止骗分,数据保证全部手造。
对于20%的数据,有n<=3。
对于60%的数据,有n<=500。
对于100%的数据,有n<=1000。
对于100%的数据,有T<=10。

#include<iostream>
#include<queue>
using namespace std;
const int maxn=1010;
int T,n,a[maxn][maxn];
bool flag[maxn][maxn];
struct node
{
    int x;
    int y;
    int t;
};
void search()
{
    queue<node> q;
    node tmp;tmp.x=1,tmp.y=1,tmp.t=1;q.push(tmp);
    while(!q.empty())
    {
        tmp=q.front();q.pop();
        if(tmp.x==n&&tmp.y==n)
        {
            cout<<"Yes"<<endl;
            return;
        }
        if(tmp.x+1<=n&&!flag[tmp.x+1][tmp.y])
        {
            if(tmp.t<=a[tmp.x+1][tmp.y]||!a[tmp.x+1][tmp.y])
            {
                node m;m.x=tmp.x+1,m.y=tmp.y,m.t=tmp.t+1;
                q.push(m);
                flag[tmp.x+1][tmp.y]=1;
            }
        }
        if(tmp.x-1>=1&&!flag[tmp.x-1][tmp.y])
        {
            if(tmp.t<=a[tmp.x-1][tmp.y]||!a[tmp.x-1][tmp.y])
            {
                node m;m.x=tmp.x-1,m.y=tmp.y,m.t=tmp.t+1;
                q.push(m);
                flag[tmp.x-1][tmp.y]=1;
            }
        }
        if(tmp.y+1<=n&&!flag[tmp.x][tmp.y+1])
        {
            if(tmp.t<=a[tmp.x][tmp.y+1]||!a[tmp.x][tmp.y+1])
            {
                node m;m.x=tmp.x,m.y=tmp.y+1,m.t=tmp.t+1;
                q.push(m);
                flag[tmp.x][tmp.y+1]=1;
            }
        }
        if(tmp.y-1>=1&&!flag[tmp.x][tmp.y-1])
        {
            if(tmp.t<=a[tmp.x][tmp.y-1]||!a[tmp.x][tmp.y-1])
            {
                node m;m.x=tmp.x,m.y=tmp.y-1,m.t=tmp.t+1;
                q.push(m);
                flag[tmp.x][tmp.y-1]=1;
            }
        }
    }
    cout<<"No"<<endl;
    return;
}
void prepare()
{
    for(int i=1;i<=n;i++)
      for(int j=1;j<=n;j++)
      flag[i][j]=0,a[i][j]=0;
}
int main()
{
    int x,y;
    cin>>T;
    while(T--)
    {
        cin>>n;
        prepare();
        for(int i=1;i<=2*n-2;i++)
        {
            cin>>x>>y;
            a[x][y]=i;
        }
        search();
    }
    return 0;
}
posted @ 2016-09-25 14:55  抽空的太阳  阅读(231)  评论(0编辑  收藏  举报