TLE求优化
查看原帖
TLE求优化
760418
not_exist楼主2024/7/7 20:51
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T,n,m;
bool mp[2005][2005],vis[2005][2005];
short xy[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char dids[5]="UDLR";

inline int read(){
	int ret=0,f=1;char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar();
    return ret*f;
}

struct Node{
	int x,y,c;
	string did;
};
queue<Node> q;

bool check(int nx,int ny,int x,int y){
	if(!(x<=n&&x>=1&&y<=m&&y>=1)){
		return false;
	}
	return (!vis[x][y])&&(mp[x][y]!=mp[nx][ny]);
}

void bfs(){
	while(!q.empty()){
		q.pop();
	}
	vis[1][1]=1;
	q.push({1,1,0,""});
	while(!q.empty()){
		Node top=q.front();
		q.pop();
		if(top.x==n&&top.y==m){
			cout<<top.c<<endl<<top.did<<endl;
			return;
		}
		for(int i=0;i<4;i++){
			int tx=top.x+xy[i][0],ty=top.y+xy[i][1];
			if(!check(top.x,top.y,tx,ty)){
				continue;
			}
			string tmp=top.did;
			tmp.push_back(dids[i]);
			q.push({tx,ty,top.c+1,tmp});
			vis[tx][ty]=1;
		}
	}
	cout<<-1<<endl;
}

signed main(){
	T=read();
	while(T--){
		n=read(),m=read();
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				vis[i][j]=0;
				char ch=getchar();
				while(!isdigit(ch)){
					ch=getchar();
				}
				mp[i][j]=ch-'0';
			}
		}
		bfs();
	}
    return 0;
}


2024/7/7 20:51
加载中...