RT。调了一个多小时了,还是不行。。。
题面:Link。
求助洛谷哇,真的调傻了……
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 505;
// 方向为右下左上
// sx[i][j] 表示当 lie = i 时,方向为 j 的 x 变化情况
// 其他类似
const int
sx[3][4] = {{0, 1, 0, -2}, {0, 1, 0, -1}, {0, 2, 0, -1}},
sy[3][4] = {{1, 0, -2, 0}, {2, 0, -1, 0}, {1, 0, -1, 0}},
slie[3][4] = {{1, 2, 1, 2}, {0, 1, 0, 1}, {2, 0, 2, 0}};
int n, m;
bool vis[MAXN][MAXN][3];
char s[MAXN][MAXN];
struct node {int x, y, lie, step;};
node st, ed;
/*
lie = 0 表示立在 (x, y)
lie = 1 表示横着,左边在 (x, y)
lie = 2 表示竖着,上边在 (x, y)
*/
queue<node> q;
void get_start_end() {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (s[i][j] == 'X' && !st.x) {
if (s[i][j + 1] == 'X') st = (node){i, j, 1, 0};
else if (s[i + 1][j] == 'X') st = (node){i, j, 2, 0};
else st = (node){i, j, 0, 0};
}
if (s[i][j] == 'O') ed = (node){i, j, 0};
}
} // 得到起点
bool cek(int x, int y) {return x >= 1 && x <= n && y >= 1 && y <= m;} // 坐标是否合法
bool check(node c) { // 状态是否合法
if (!cek(c.x, c.y)) return false;
if (s[c.x][c.y] == '#') return false;
if (!c.lie && s[c.x][c.y] != '.') return false;
if (c.lie == 1 && (!cek(c.x, c.y + 1) || s[c.x][c.y + 1] == '#')) return false;
if (c.lie == 2 && (!cek(c.x + 1, c.y) || s[c.x + 1][c.y] == '#')) return false;
return true;
}
int bfs() {
while (q.size()) q.pop();
q.push(st);
memset(vis, false, sizeof(vis));
while (q.size()) {
node now = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
node nxt;
nxt.x = now.x + sx[now.lie][i];
nxt.y = now.y + sy[now.lie][i];
nxt.lie = slie[now.lie][i];
if (!check(nxt) || vis[nxt.x][nxt.y][nxt.lie]) continue;
nxt.step = now.step + 1;
vis[nxt.x][nxt.y][nxt.lie] = true;
q.push(nxt);
if (nxt.x == ed.x && nxt.y == ed.y && nxt.lie == ed.lie) return nxt.step;
}
}
return -1;
}
int main() {
while (~scanf("%d %d", &n, &m) && n) {
for (int i = 1; i <= n; i++) scanf("%s", s[i] + 1);
get_start_end();
int ans = bfs();
cout << ans << endl;
}
return 0;
}