题面
题意:
- 给出一个 n*m 的水管图,要从 (1,1) 顶部走到 (n,m) 底部。每走一步前,可以选择一个管道集合旋转相同的角度。要求在 20nm 步前走到终点或者输出无解。
思路:
- 给了六种水管,其中1-4类型的水管都可以通过旋转互相转换,5-6类型的水管也可以通过旋转互相转换。因此我们其实每次走到下一个点的时候只需要判断当前的水管类型,如果当前水管类型为1-4的类型,那么就根据你进入的方向,来得到你如果转向的方向,例如你如果是方向向下进入的,你当前遇到的水管类型是1-4里面的,那么你下一步就只能向右或左边行走。但如果你遇到的水管类型为5-6的话,你只能继续朝着你进来的方向继续前进。水管的类型只会影响这两个。因此查找是否存在路径,我们就bfs里面判一下这两种不同类型的情况就可以了。
- 记录路径。我们利用一个三纬结构体来记录路径,分别记录当前x,y,dir的前驱为什么,后面通过搜索来遍历路径,同时需要根据进入的方向和出去的方向来得到水管的类型,我们通过一个type数组来对其进行转换即可。
代码:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3 + 10;
int n, m;
int mp[MAXN][MAXN];
int dirx[4] = {1, 0, -1, 0};
int diry[4] = {0, -1, 0, 1};
bitset<MAXN> vis[4][MAXN];
int type[4][4] = {
{5, 0, -1, 1},
{2, 4, 1, -1},
{-1, 3, 5, 2},
{3, -1, 0, 4},
};
struct node {
int x, y, dir;
} pre[MAXN][MAXN][4];
bool check(int x, int y, int dir) {
if (x == n + 1 && y == m && dir == 0) {
return true;
}
if (x < 1 || x > n || y < 1 || y > m || vis[dir][x][y]) {
return false;
}
return true;
}
bool bfs() {
queue<node> q;
q.push({1, 1, 0});
vis[0][1][1] = true;
while (!q.empty()) {
int nowx, nowy, nowdir, nextx, nexty, nextdir;
node tmp = q.front();
q.pop();
nowx = tmp.x;
nowy = tmp.y;
nowdir = tmp.dir;
if (mp[nowx][nowy] < 4) {
nextdir = (nowdir + 1) % 4;
nextx = nowx + dirx[nextdir];
nexty = nowy + diry[nextdir];
if (check(nextx, nexty, nextdir)) {
q.push({nextx, nexty, nextdir});
vis[nextdir][nextx][nexty] = true;
pre[nextx][nexty][nextdir] = tmp;
}
if (nextx == n + 1 && nexty == m && nextdir == 0) {
return true;
}
nextdir = (nowdir + 3) % 4;
nextx = nowx + dirx[nextdir];
nexty = nowy + diry[nextdir];
if (check(nextx, nexty, nextdir)) {
q.push({nextx, nexty, nextdir});
vis[nextdir][nextx][nexty] = true;
pre[nextx][nexty][nextdir] = tmp;
}
if (nextx == n + 1 && nexty == m && nextdir == 0) {
return true;
}
} else {
nextdir = nowdir;
nextx = nowx + dirx[nextdir];
nexty = nowy + diry[nextdir];
if (check(nextx, nexty, nextdir)) {
q.push({nextx, nexty, nextdir});
vis[nextdir][nextx][nexty] = true;
pre[nextx][nexty][nextdir] = tmp;
}
if (nextx == n + 1 && nexty == m && nextdir == 0) {
return true;
}
}
}
return false;
}
void dfs(int step, int x, int y, int dir) {
if (x == 1 && y == 1 && dir == 0) {
printf("%d\n", step * 2);
return;
}
node tmp = pre[x][y][dir];
dfs(step + 1, tmp.x, tmp.y, tmp.dir);
int k = type[tmp.dir][dir];
printf("1 %d %d %d\n", (k - mp[tmp.x][tmp.y] + 4) % 4 * 90, tmp.x, tmp.y);
mp[tmp.x][tmp.y] = k;
printf("0 %d %d\n", tmp.x, tmp.y);
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
memset(vis, false, sizeof(vis));
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%d", &mp[i][j]);
}
}
if (bfs()) {
puts("YES");
dfs(0, n + 1, m, 0);
} else {
puts("NO");
}
}
return 0;
}