BFS 注意起点和终点相同的情况
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main{
static String s0,s1;
static String[] str = {"LU","U","RU","R","RD","D","LD","L"};
static int[][] next = {{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0}};
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
s0 = sc.next();
s1 = sc.next();
bfs();
}
}
public static void bfs(){
int x0 = Integer.valueOf(s0.charAt(0)-'a');
int y0 = Integer.valueOf(s0.substring(1));
int x1 = Integer.valueOf(s1.charAt(0)-'a');
int y1 = Integer.valueOf(s1.substring(1));
Queue<Node> queue = new LinkedList<>();
boolean[][] flag = new boolean[10][10];
flag[x0][y0] = true;
queue.add(new Node(x0,y0,0,""));
if(x0==x1&&y0==y1){
System.out.println(0);
return;
}
while(queue.size()>0){
Node no = queue.poll();
int x = no.x;
int y = no.y;
int s = no.s;
String b = no.book;
for(int i=0;i<8;i++){
int ts = s+1;
int tx = x+next[i][0];
int ty = y+next[i][1];
String tb = b+str[i]+"
";
if(tx<0||tx>=8||ty<1||ty>8) continue;
if(flag[tx][ty]) continue;
flag[tx][ty] = true;
if(tx==x1&&ty==y1){
System.out.println(ts);
System.out.println(tb);
return;
}
queue.add(new Node(tx,ty,ts,tb));
}
}
}
}
class Node{
int x,y,s;
String book;
Node(int x,int y,int s,String book){
this.x = x;
this.y = y;
this.s = s;
this.book = book;
}
}