RE求调
查看原帖
RE求调
1206892
further20120229楼主2025/7/30 10:10
#include <bits/stdc++.h>
using namespace std;

#define ll long long
const int N=1e3+10;
const int M=1e6+10;

int T,n,m;
int f[5][2]={{0,0},{-1,0},{1,0},{0,-1},{0,1}},vis[N][N];
char a[N][N],wh[4]={'U','D','L','R'};
stack<char> st;

struct node{
	int x,y;
	char num;
	int sum,whe;
};

inline void myprintf(int d){
	int posx,posy;
	posx=n,posy=m;
	while(d--){
		if(vis[posx][posy]==1){
			st.push(wh[0]);
			posx++;
		}else if(vis[posx][posy]==2){
			st.push(wh[1]);
			posx--;
		}else if(vis[posx][posy]==3){
			st.push(wh[2]);
			posy++;
		}else if(vis[posx][posy]==4){
			st.push(wh[3]);
			posy--;
		}
	}
	while(!st.empty()){
		cout<<st.top();
		st.pop();
	}
	cout<<'\n';
}

inline void BFS(int x,int y,char z){
	queue<node> q;
	q.push({x,y,z,0,-1});
	while(!q.empty()){
		int xx=q.front().x,yy=q.front().y,sum=q.front().sum,whe=q.front().whe;
		char num=q.front().num;
		q.pop();
		if(vis[xx][yy]||a[xx][yy]!=num||xx<1||xx>n||yy<1||yy>m){
			continue;
		}
		vis[xx][yy]=whe;
		if(xx==n&&yy==m){
			cout<<sum<<'\n';
			myprintf(sum);
			return ;
		}
		for(int i=1;i<=4;i++){
			q.push({xx+f[i][0],yy+f[i][1],(1-(num-'0'))+'0',sum+1,i});
		}
	}
	cout<<-1<<'\n';
	return ;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(0);
	cin>>T;
	while(T--){
		cin>>n>>m;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				cin>>a[i][j];
			}
		}
		memset(vis,0,sizeof(vis));
		BFS(1,1,a[1][1]);
	}
	return 0;
}
2025/7/30 10:10
加载中...