求条
查看原帖
求条
1432246
_qumingnan_楼主2025/1/9 17:13
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,t;
queue<pair<int,int> >q;
int a[1005][1005],ans;
int b[1005][1005];
int c[]={1,0,-1,0};
int d[]={0,1,0,-1};
char ch[1005][1005],chh[]={'D','R','U','L'};
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>t;
	while(t--){
		cin>>n>>m;
		if(n==1&&n==m){cout<<"0\n";continue;}
		for(int i=1;i<=n;i++){
			string s;cin>>s;
			for(int j=1;j<=m;j++)a[i][j]=s[j-1]-'0';
		}
		q.push({1,1});
		bool bb=0;
		while(!q.empty()){
			pair<int,int>p=q.front();q.pop();
			for(int i=0;i<4;i++){
				int x=p.first+c[i],y=p.second+d[i];
				if(x>0&&x<=n&&y>0&&y<=m&&!b[x][y]&&a[x][y]!=a[p.first][p.second]){
					ch[x][y]=chh[i];
					b[x][y]=b[p.first][p.second]+1;
					q.push({x,y});
					if(x==n&&y==m){
						cout<<b[x][y]<<'\n';
						int xx=x,yy=y;
						string s="";
						for(int i=1;i<=b[x][y];i++){
							s=ch[xx][yy]+s;
							if(ch[xx][yy]=='U')xx++;
							if(ch[xx][yy]=='D')xx--;
							if(ch[xx][yy]=='L')yy++;
							if(ch[xx][yy]=='R')yy--;
						}
						cout<<s;
						bb=1;
						break;
					}
				}
			}
			if(bb)break;
		}
		if(!bb)cout<<-1<<'\n';
		while(!q.empty())q.pop();
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++)b[i][j]=0,ch[i][j]=' ';
	}
	return 0;
}
2025/1/9 17:13
加载中...