import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class bfs_migong {
static int n,m;
static int[][] map = new int[100][100];
static boolean[][] vis = new boolean[100][100];
static int[] X = new int[]{1,0,0,-1};//D L R U
static int[] Y = new int[]{0,-1,1,0};//D L R U
static String[] path = new String[]{"D","L","R","U"};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for(int i = 1;i<=n;i++){
String s = sc.next();//用next截取每一行
for(int j = 1;j<=m;j++){
map[i][j] = s.charAt(j-1);
}
}
bfs();
}
public static void bfs(){
Queue<Node> q = new LinkedList<>();//队列
q.offer(new Node(0,"",1,1));//先存起点
while (!q.isEmpty()){
Node top = q.poll();//poll
vis[top.x][top.y] = true;//vis -> true
if(top.x == n && top.y == m){//先检查是否到达终点
System.out.println(top.path);//打印路径
System.out.println(top.step);//打印步数
return;
}
for(int i = 0;i<4;i++){//若没到终点则继续搜索路径
int newX = top.x + X[i];
int newY = top.y + Y[i];
if(check(newX,newY)){
Node node = new Node(top.step+1,top.path+path[i],newX,newY);
q.offer(node);
}
}
}
}
public static boolean check(int x,int y){
if(x<1 || x>n || y<1 || y>m){
return false;
}
if(vis[x][y] == true || map[x][y] == '1'){
return false;
}
return true;
}
}
class Node{
int step;
String path;
int x,y;
public Node(int step, String path, int x, int y) {
super();
this.step = step;
this.path = path;
this.x = x;
this.y = y;
}
}
蓝桥杯 迷宫 JAVA——BFS
最新推荐文章于 2024-05-21 19:15:40 发布