Code:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
const int N = 1010, TN = 2 * N;
typedef std::pair<int, int> PII;
int T, n;
bool g[N][N], vis[N][N];
PII zz[TN];
struct Node { int x, y, times; };
bool bfs()
{
std::queue<Node> q;
q.push((Node){1, 1, 0});
vis[1][1] = 1;
while (q.size())
{
auto t = q.front(); q.pop();
if (t.x == n && t.y == n) return true;
g[zz[t.times - 1].first][zz[t.times - 1].second] = 1;
for (int i = 0; i < 4; i ++ )
{
int xx = t.x + dx[i], yy = t.y + dy[i];
if (xx >= 1 && xx <= n && yy >= 1 && yy <= n && !g[xx][yy] && !vis[xx][yy])
{
vis[xx][yy] = true;
q.push((Node){xx, yy, t.times + 1});
}
}
}
return false;
}
int main()
{
scanf("%d", &T);
while (T -- )
{
memset(vis, 0, sizeof vis);
memset(g, -1, sizeof g);
scanf("%d", &n);
for (int i = 0; i < 2 * n - 2; i ++ )
scanf("%d%d", &zz[i].first, &zz[i].second);
if (bfs()) puts("Yes");
else puts("No");
}
return 0;
}
