迷宫 - 蓝桥云课 (lanqiao.cn)
public class N602 {
static char[][] m = new char[30][50];
static char[] d = { 'D', 'L', 'R', 'U' };// 定义这个顺序为字典序答案就是最小字典序
static int[][] dir = { { 1, 0 }, { 0, -1 }, { 0, 1 }, { -1, 0 } };// 方向数组的序号与上面的对应
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 30; i++) {// 输入
String s = scanner.next();
for (int j = 0; j < 50; j++) {
m[i][j] = s.charAt(j);
}
}
bfs();// 广搜
}
static void bfs() {
LinkedList<Node> q = new LinkedList<>();// 定义一个队列
m[0][0] = '1';// 广搜仅走一次
q.addLast(new Node(0, 0));// 第一个节点入队
while (!q.isEmpty()) {
Node next, now;
now = q.removeFirst();
if (now.x == 29 && now.y == 49) {
System.out.println(now.s);
}
for (int i = 0; i < 4; i++) {
next = new Node(now.x + dir[i][0], now.y + dir[i][1]);
if (next.x >= 0 && next.x <= 29 && next.y >= 0 && next.y <= 49 && m[next.x][next.y] == '0') {// 符合条件入队
next.s = now.s + d[i];// 字符串拼接
q.addLast(next);
m[next.x][next.y] = '1';
}
}
}
}
}
class Node {
int x;
int y;
String s;
public Node(int x, int y) {
this.x = x;
this.y = y;
this.s = "";
}
}