WA #16
查看原帖
WA #16
1224537
666nnnzzz楼主2024/3/29 14:17
#include<iostream>
#include<queue>
#include<string>
#include<vector>
using namespace std;
typedef struct Node{
	char value;
	bool gone;
}node;

node a[2005][2005];
int main()
{

	int T;
	for(cin>>T;T;--T){
		string end;
		int n,m;
		cin>>n>>m;
		
		
		char rec[n][m]={};
		for(int i=0;i<n;++i){
			for(int j=0;j<m;++j){
				cin>>a[i][j].value;

				a[i][j].gone=false;
			}
		}
		queue<int> q;
		q.push(0);
		q.push(0);
		while(!q.empty()){
		
			int x=q.front();
			q.pop();
			int y=q.front();
			
			if(x==(n-1)&&y==(m-1))
			{
				
				int x=n-1;
				int y=m-1;
				while(x!=0||y!=0){
					end=rec[x][y]+end;
					if(rec[x][y]=='U'){
						x=x+1;
					}
					else if(rec[x][y]=='D'){
						x=x-1;
					}
					else if(rec[x][y]=='L'){
						y=y+1;
					}
					else if(rec[x][y]=='R'){
						y=y-1;
					}
		
				}
			
				cout<<end.size()<<endl;
				cout<<end<<endl;
				
				break;
			}
			if(x>1&&a[x][y].value!=a[x-1][y].value&&a[x-1][y].gone==false){
				q.push(x-1);
				q.push(y);
				a[x-1][y].gone=true;
				rec[x-1][y]='U';
				
			}
			if(x<n-1&&a[x][y].value!=a[x+1][y].value&&a[x+1][y].gone==false){
				q.push(x+1);
				q.push(y);
				a[x+1][y].gone=true;
				rec[x+1][y]='D';
			
			}
			if(y>1&&a[x][y].value!=a[x][y-1].value&&a[x][y-1].gone==false){
				q.push(x);
				q.push(y-1);
				a[x][y-1].gone=true;
				rec[x][y-1]='L';
			
			}
			if(y<m-1&&a[x][y].value!=a[x][y+1].value&&a[x][y+1].gone==false){
				q.push(x);
				q.push(y+1);
				a[x][y+1].gone=true;
				rec[x][y+1]='R';
				
			}
			q.pop();
		}
		if(end.size()==0&&n!=0)cout<<"-1"<<endl;	
	}	
}
2024/3/29 14:17
加载中...