P3395 路障
题目描述
B 君站在一个 n×nn\times nn×n 的棋盘上。最开始,B君站在 (1,1)(1,1)(1,1) 这个点,他要走到 (n,n)(n,n)(n,n) 这个点。
B 君每秒可以向上下左右的某个方向移动一格,但是很不妙,C 君打算阻止 B 君的计划。
每秒结束的时刻,C 君 会在 (x,y)(x,y)(x,y) 上摆一个路障。B 君不能走在路障上。
B 君拿到了 C 君准备在哪些点放置路障。所以现在你需要判断,B 君能否成功走到 (n,n)(n,n)(n,n)。
保证数据足够弱:也就是说,无需考虑“走到某处然后被一个路障砸死”的情况,因为答案不会出现此类情况。
输入格式
首先是一个正整数 TTT,表示数据组数。
对于每一组数据:
第一行,一个正整数 nnn。
接下来 2n−22n-22n−2 行,每行两个正整数 xxx 和 yyy,意义是在那一秒结束后,(x,y)(x,y)(x,y) 将被摆上路障。
输出格式
对于每一组数据,输出 Yes
或 No
,回答 B 君能否走到 (n,n)(n,n)(n,n)。
输入输出样例 #1
输入 #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%20\%20% 的数据,有 n≤3n\le3n≤3。
对于 60%60\%60% 的数据,有 n≤500n\le500n≤500。
对于 100%100\%100% 的数据,有 n≤1000n\le1000n≤1000。
对于 100%100\%100% 的数据,有 T≤10T\le10T≤10。
题解
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+7;
int T, n;
int t[N][N];
bool vis[N][N];
int rx[] = {0, 0, -1, 0, 1}, ry[] = {0, -1, 0, 1, 0};//左上右下
struct pl{
int x, y, ti;
};
queue<pl> pass;
bool flag = 0;
void bfs(){
vis[1][1] = 1;
while(!pass.empty()){
pl pass1 = pass.front();
pass.pop();
for(int i=1;i<=4;++i){
int nx = rx[i] + pass1.x;
int ny = ry[i] + pass1.y;
if(nx<=0 || nx>n || ny<=0 || ny>n || vis[nx][ny]) continue;
if((pass1.ti+1 > t[nx][ny]) && t[nx][ny] != 0) {
vis[nx][ny] = 1;
continue;
}
if(nx == n && ny == n) {
flag = 1;
return ;
}
vis[nx][ny] = 1;
pass.push({nx, ny, pass1.ti+1});
}
if(flag) return ;
}
return ;
}
int main(){
cin>>T;
while(T--){
int x,y;
cin>>n;
if(n == 1) {
cout<<"Yes"<<endl;
continue;
}
flag = 0;
memset(vis, 0, sizeof(vis));
while(!pass.empty()) pass.pop();//初始化
memset(t, 0, sizeof(t));
for(int i=1;i<=2*n-2;++i){
cin>>x>>y;
t[x][y] = i+1;
}
pass.push({1,1,1});
bfs();
if(flag){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}
return 0;
}