【ACM- OJ】《路障》C++
题目描述
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)。
样例输入
2
2
1 1
2 2
5
3 3
3 2
3 1
1 2
1 3
1 4
1 5
2 2
样例输出
Yes
Yes
AC代码
//
// main.cpp
// 路障
//
// Created by HISS on 2020/11/6.
// Copyright © 2020 HISS. All rights reserved.
//
#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;
}