div2 b 求条
  • 板块灌水区
  • 楼主nightwatch.ryan
  • 当前回复1
  • 已保存回复1
  • 发布时间2024/3/9 18:08
  • 上次更新2024/3/9 20:10:12
查看原帖
div2 b 求条
961351
nightwatch.ryan楼主2024/3/9 18:08
#include<iostream>

#include<climits>

#include<queue>

#include<cstring>

#include<cstdio>

#include<map>

#define N 2005

int mp[N][N];

const int dx[4]={-1,1,0,0};

const int dy[4]={0,0,-1,1};

void bfs(int n,int m){

	int dist[n+1][m+1];

	for(int i=1;i<=n;i++)

		for(int j=1;j<=m;j++)

			dist[i][j]=INT_MAX;

	dist[1][1]=0;

	int pa[n+1][m+1]={0},pb[n+1][m+1]={0};

	std::queue<std::pair<int,int>>q;

	q.push({1,1});

	while(q.size()){

		std::pair<int,int>u=q.front();q.pop();

		for(int i=0;i<4;i++){

			int nextX=u.first+dx[i];

			int nextY=u.second+dy[i];

			if(nextX>=1 and nextX<=n and nextY>=1 and nextY<=m and mp[nextX][nextY]!=mp[u.first][u.second]){

				if(dist[nextX][nextY]==INT_MAX){

					int temp=dist[u.first][u.second]+1; 

					if(temp<dist[nextX][nextY]){

						dist[nextX][nextY]=temp;

						pa[nextX][nextY]=u.first;

						pb[nextX][nextY]=u.second;

						q.push({nextX,nextY}); 

					}

				}

			}

		}

	}

	if(dist[n][m]==INT_MAX){

		std::cout<<"-1\n";

		return;

	}

	std::cout<<dist[n][m]<<'\n'; 

	int curX=n,curY=m; 

	std::string r;

	while(curX!=1 or curY!=1){

		int lastX=pa[curX][curY];

		int lastY=pb[curX][curY];

		if(lastX<curX)r="D"+r;

		else if(lastX>curX)r="U"+r;

		else if(lastY<curY)r="R"+r;

		else r="L"+r;

		curX=lastX;curY=lastY;

	}

	std::cout<<r<<'\n';

}

int main(){

	//std::ios::sync_with_stdio(0);

	int t;std::cin>>t;

	while(t--){

		int n,m;std::cin>>n>>m;

		for(int i=1;i<=n;i++)

			for(int j=1;j<=m;j++)

				scanf("%1d",&mp[i][j]);

		bfs(n,m);

		memset(mp,0,sizeof(mp));

	}

}

rt赛时一直tle

2024/3/9 18:08
加载中...