求助 TLE #16
查看原帖
求助 TLE #16
1220111
xiaoyang222楼主2024/3/9 21:35
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int dx[]={-1,0,1,0},dy[]={0,1,0,-1};
const char d[]={'U','R','D','L'};
struct Node{
	int a,b;
	string s;
	Node()=default;
	explicit Node(int a,int b,string s) : a(a),b(b),s(s) {}
};
void solve(){
	int n,m;
	scanf("%d%d",&n,&m);
	vector<vector<short>> maze(n+1,vector<short>(m+1));
	for (int i=1;i<=n;++i){
		getchar();
		for (int j=1;j<=m;++j){
			maze[i][j]=getchar()-'0';
			if ((i+j)%2==0){
				maze[i][j]=1-maze[i][j];
			}
		}
	}
	if (maze[1][1]!=maze[n][m]){
		printf("-1\n");
		return;
	}
	queue<Node> q;
	q.emplace(1,1,"");
	vector<vector<bool>> st(n+1,vector<bool>(m+1,false));
//	a[1][1]="";
	st[1][1]=true;
	int tx,ty,x,y;
	int i,len;
	string str;
	while (!q.empty()){
		x=q.front().a,y=q.front().b,str=q.front().s;
		q.pop();
		if (x==n && y==m){
			cout<<str.size()<<endl<<str<<endl;
			return;
		}
		str.push_back('?');
		len=str.size()-1;
		for (i=0;i<4;++i){
			tx=x+dx[i],ty=y+dy[i];
			if (tx<=0 || tx>n || ty<=0 || ty>m || st[tx][ty] || maze[tx][ty]!=maze[x][y]){
				continue;
			}
			st[tx][ty]=true;
			str[len]=d[i];
			q.emplace(tx,ty,str);
		}
	}
	printf("-1\n");
}
int main(){
	int T;
	cin >> T;
	for (int i=0;i<T;++i){
		solve();
	}
	return 0;
}
2024/3/9 21:35
加载中...