tle 16
查看原帖
tle 16
1082760
huxint楼主2024/3/10 13:24

我觉得代码应该没啥问题,为什么会tle(开了O2)

#include <bits/stdc++.h>
using namespace std;
struct node {
	int x, y, d;
	string path;
};
int dx[] = {0, 1, 0, -1, 1, -1, 1, -1}, dy[] = {1, 0, -1, 0, 1, 1, -1, -1};
void solve() {
	int n, m;
	cin >> n >> m;
	vector<vector<char>> a(n + 1, vector<char>(m + 1));
	vector<vector<int>> st(n + 1, vector<int>(m + 1));
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			cin >> a[i][j];
	queue<node> Q;
	Q.push({1, 1, 0, ""});
	st[1][1] = true;
	while (Q.size()) {
		auto [x, y, d, path] = Q.front();
		Q.pop();
		if (x == n and y == m) {
			cout << d << '\n' << path << '\n';
			return;
		}
		for (int i = 0; i < 4; ++i) {
			int xx = x + dx[i], yy = y + dy[i];
			if (xx >= 1 and xx <= n and yy >= 1 and yy <= m and !st[xx][yy] and a[xx][yy] != a[x][y]) {
				st[xx][yy] = 1;
				Q.push({xx, yy, d + 1, path + (i == 0 ? 'R' : i == 1 ? 'D' : i == 2 ? 'L' : 'U')});
			}
		}
	}
	cout << -1 << '\n';
}

int main() {
	std::ios::sync_with_stdio(false), std::cin.tie(nullptr);
	int T = {1};
	std::cin >> T;
	while (T--) solve();
	return 0;
}
2024/3/10 13:24
加载中...