蓝桥杯 算法提高 学霸的迷宫
题目描述
学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗。但学霸为了不要别人打扰,住在一个城堡里,城堡外面是一个二维的格子迷宫,要进城堡必须得先通过迷宫。因为班长还有妹子要陪,磨刀不误砍柴功,他为了节约时间,从线人那里搞到了迷宫的地图,准备提前计算最短的路线。可是他现在正向妹子解释这件事情,于是就委托你帮他找一条最短的路线。
输入
第一行两个整数n, m,为迷宫的长宽。
接下来n行,每行m个数,数之间没有间隔,为0或1中的一个。0表示这个格子可以通过,1表示不可以。假设你现在已经在迷宫坐标(1,1)的地方,即左上角,迷宫的出口在(n,m)。每次移动时只能向上下左右4个方向移动到另外一个可以通过的格子里,每次移动算一步。数据保证(1,1),(n,m)可以通过。
输出
第一行一个数为需要的最少步数K。
第二行K个字符,每个字符∈{U,D,L,R},分别表示上下左右。如果有多条长度相同的最短路径,选择在此表示方法下字典序最小的一个。
样例输入
3 3
001
100
110
样例输出
4
RDRD
package dotcppTraining;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class P_迷宫最短路径 {
static int n;
static int m;
static char[][] graph ;
static Queue<GraphNode> q = new LinkedList<>();
static int[][] dis;
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] a = bf.readLine().split(" ");
n = Integer.parseInt(a[0]);
m = Integer.parseInt(a[1]);
dis = new int[n][m];
graph = new char[n][m];
for (int i = 0; i < dis.length; i++) {
for (int j = 0; j < dis[i].length; j++) {
dis[i][j] = -1;
}
}
dis[n-1][m-1] = 0;
for (int i = 0; i < graph.length; i++) {
graph[i] = bf.readLine().toCharArray();
}
q.add(new GraphNode(n-1,m-1));
bfs(); //bfs找出每个点到达终点的最短距离
int x = 0;
int y = 0;
String res = "";
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && graph[nx][ny] == '0' && dis[nx][ny] != -1){
if(dis[x][y] == dis[nx][ny] + 1){
res += dir[i];
x = nx;
y = ny;
i = -1; //重置 i ,为了维持字典序
}
}
}
System.out.println(res);
}
static char[] dir= {'D','L','R','U'};
static int[] dx = {1,0,0,-1};
static int[] dy = {0,-1,1,0};
private static void bfs() {
while(!q.isEmpty()){
GraphNode node = q.poll();
int x = node.x;
int y = node.y;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && graph[nx][ny] == '0'&& dis[nx][ny] == -1){
q.add(new GraphNode(nx, ny));
dis[nx][ny] = dis[x][y] + 1;
}
}
}
System.out.println(dis[0][0]);
}
}
class GraphNode{
public int x;
public int y;
public GraphNode(int x, int y) {
super();
this.x = x;
this.y = y;
}
}