WA求助(玄关)
查看原帖
WA求助(玄关)
770891
NTT__int128楼主2024/3/16 21:57
#include <bits/stdc++.h>
using namespace std ;
int t , n , m ;
char c[2005][2005] ;
int to[2005][2005] ;
int step[2005][2005] ;
int dx[4] = {0 , 1 , 0 , -1} ;
int dy[4] = {-1 , 0 , 1 , 0} ;
char sz[4] = {'U' , 'R' , 'D' , 'L'} ;
struct node
{
	int x , y ;
} ;
queue <node> q , cl ;
void bfs()
{
	step[1][1] = 0 ;
	q = cl ;
	q.push({1 , 1}) ;
	while(!q.empty())
	{
		node tmp = q.front() ;
		q.pop() ;
		for(int i = 0 ; i < 4 ; i++)
		{
			int nx = tmp.x + dx[i] , ny = tmp.y + dy[i] ;
			if(nx < 1 || nx > n || ny < 1 || ny > m)	continue ;
			if(step[nx][ny] != -1 || c[nx][ny] == c[tmp.x][tmp.y])	continue ;
			step[nx][ny] = step[tmp.x][tmp.y] + 1 ;
			q.push({nx , ny}) ;
			to[nx][ny] = i ;
		}
	}
	return ;
}
void dfs(int x , int y)
{
	if(x == 1 && y == 1)	return ;
	dfs(x - dx[to[x][y]] , y - dy[to[x][y]]) ;
	cout << sz[to[x][y]] ;
}
int main()
{
	ios::sync_with_stdio(0) ;
	cin.tie(0) ;
	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 >> c[i][j] ;
		}
		memset(step , -1 , sizeof(step)) ;
		bfs() ;
		if(step[n][m] == -1)
		{
			cout << "-1\n" ;
			continue ;
		}
		cout << step[n][m] << "\n" ;
		dfs(n , m) ;
		cout << "\n" ;
	}
	return 0 ;
}
2024/3/16 21:57
加载中...