RE 0pts求条
查看原帖
RE 0pts求条
1140231
ChangeYuAN楼主2025/1/18 11:35
#include <bits/stdc++.h>
using namespace std;
const int MAXLEN = 505;

int mp[MAXLEN][MAXLEN] = {0}, T, n, m;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
char sign[4] = {'R', 'D', 'L', 'U'};
bool vis[MAXLEN][MAXLEN] = {false};
char path[MAXLEN][MAXLEN];
struct node {
	int x, y;
	char from;
};
queue<node> q;
stack<char> s;

signed main() {
	cin >> T;
	while (T--) {
		memset(vis, false, sizeof(vis));
		cin >> n >> m;
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= m; j++) {
				char ch = getchar();
				while (ch != '0' && ch != '1') {
					ch = getchar();
				}
				mp[i][j] = ch - '0';
			}
		}
		q.push({1, 1, '0'});
		while (!q.empty()) {
			node u = q.front();
			q.pop();
			if (vis[u.x][u.y] || u.x > n || u.x < 1 || u.y > m || u.y < 1)
				continue;
			path[u.x][u.y] = u.from;
			vis[u.x][u.y] = true;
			for (int i = 0; i < 4; i++) {
				int nx = u.x + dx[i], ny = u.y + dy[i];
				if (mp[nx][ny] == mp[u.x][u.y])
					continue;
				q.push({nx, ny, sign[i]});
			}
		}
		if (!vis[n][m]) {
			cout << "-1\n";
			continue;
		}
		int i = n, j = m;
		while (1) {
			if (i == 1 && j == 1)
				break;
			s.push(path[i][j]);
			if (path[i][j] == 'D') {
				i--;
				continue;
			}
			if (path[i][j] == 'U') {
				i++;
				continue;
			}
			if (path[i][j] == 'R') {
				j--;
				continue;
			}
			if (path[i][j] == 'L') {
				j++;
				continue;
			}
		}
		cout << s.size() << '\n';
		while (!s.empty()) {
			cout << s.top();
			s.pop();
		}
		cout << '\n';
	}
}
2025/1/18 11:35
加载中...