#WA1 求助
查看原帖
#WA1 求助
987758
CaoSheng_zzz楼主2024/7/26 20:30
#include <algorithm>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <map>
#define ll long long
#define prt printf
#define fir first
#define se second
using namespace std;

int read(){
	int f = 1 , k = 0;
	char c = getchar();
	while(c < '0' || c > '9'){
		if(c == '-') f = -1;
		c = getchar() ;
	}
	while('0' <= c && c <= '9'){
		k = (k << 3) + (k << 1) + (c ^ 48);
		c = getchar();
	}
	return (f == -1 ? -k : k);
}

int red(){
	char c = getchar();
	while(c < '0' || c > '9') c = getchar() ;
	return (c ^ 48);
}

const int maxn = 2e3 + 1;
const int dx[] = {0 , -1 , 1 , 0 , 0};
const int dy[] = {0 , 0 , 0 , -1 , 1};
int t , n , m;
int a[maxn][maxn] , vis[maxn][maxn];

void bfs(){
	queue<pair<int , int>>q ; memset(vis , 0 , sizeof vis) ; queue<pair<int , string>> p;
	q.push({1 , 1}) ; p.push({0 , " "}) ; vis[1][1] = 1;
	while(! q.empty()){
		int x = q.front().fir , y = q.front().se ; q.pop() ;
		string s = p.front().se ; int num = p.front().fir ; p.pop() ;
		for(int i=1 ; i<=4 ; i++){
			int xx = x + dx[i] , yy = y + dy[i];
			if(vis[xx][yy] == 0 && (a[xx][yy] ^ a[x][y]) == 1 && 0 < xx && xx <= n && 0 < yy && yy<=m){
				q.push({xx , yy}) ; ++ num ;
				if(i == 1) s += 'U';
				if(i == 2) s += 'D';
				if(i == 3) s += 'L';
				if(i == 4) s += 'R';
				if(xx == n && yy == m){
				 	prt("%d\n" , num);
				 	for(int i=1 ; i<=num ; i++) prt("%c" , s[i]);
				 	prt("\n");
					return ;
				}
				p.push({num , s});
				vis[xx][yy] = 1;
			}
		}
	}
	while(! q.empty()) { q.pop() , p.pop() ;}
	prt("-1\n") ;
	return ;
}

signed main(){
	t = read() ;
	while(t --){
		n = read() , m = read() ;
		for(int i=1 ; i<=n ; i++){
			for(int j=1 ; j<=m ; j++) a[i][j] = red();
		}
		bfs();
	}
	return 0;
}
2024/7/26 20:30
加载中...