P1455 - [蓝桥杯2019初赛]迷宫 - New Online Judgehttp://oj.ecustacm.cn/problem.php?id=1455
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef long long ll;
int g[64][64] = { 0 };
int vis[64][64] = { 0 };
int di[] = { 1, 0, 0, -1 }; // 下 左 右 上
int dj[] = { 0, -1, 1, 0 };
char m[] = { 'D','L','R','U' };
char pre[64][64];
int width, height;
int check(int i, int j) {
if (i < 1 || j < 1 || i > height || j > width) {
return 0;
}
if (vis[i][j] || g[i][j]) {
return 0;
}
return 1;
}
void bfs() {
queue<pair<int, int> >q;
q.push({ 1,1 });
vis[1][1] = 1;
while (!q.empty()) {
int t = q.front().first;
int y = q.front().second;
q.pop();
for (int dir = 0; dir < 4; dir++) {
int i = t + di[dir];
int j = y + dj[dir];
if (i == height && j == width) {
vector<char>res;
pre[i][j] = m[dir];
while (!(i == 1 && j == 1)) {
printf("i=%d, j=%d\n", i, j);
printf("pre[%d][%d]=%c\n", i, j, pre[i][j]);
res.push_back(pre[i][j]);
for (int dir = 0; dir < 4; dir++) {
if (pre[i][j] == m[dir]) {
i -= di[dir];
j -= dj[dir];
break;
}
}
}
for (int i = res.size() - 1; i >= 0; i--) {
cout << res[i];
}
cout << endl;
return;
}
if (check(i, j)) {
q.push({ i,j });
pre[i][j] = m[dir];
vis[i][j] = vis[t][y] + 1;
}
}
}
}
int main() {
// system("chcp 65001");
freopen("C:/Users/zhaochen/Desktop/input.txt", "r", stdin);
cin.tie(0);
cout.tie(0);
string str;
int line = 0;
while (getline(cin, str)) {
line++;
for (int i = 1; i <= str.length(); i++) {
g[line][i] = str[i - 1] - '0';
}
}
height = line;
width = str.length();
bfs();
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= width; j++) {
cout << vis[i][j] << " ";
}
cout << endl;
}
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= width; j++) {
if (g[i][j]) {
cout << " ";
}
cout << pre[i][j] << " ";
}
cout << endl;
}
return 0;
}