package javaDemo;
import java.util.Scanner;
import java.util.LinkedList;
public class migong{
//表示迷宫的结点,包括当前路径字符串
static class Node{
int x;
int y;
String str;
public Node(int x,int y,String str) {
this.x=x;
this.y=y;
this.str=str;
}
}
//定义需要的类
static char[][]graph =new char[30][50];
//根据字典序从小到大排,所以搜索的时候就按这个顺序
static char[]path= {'D','L','R','U'};
//分别对应字典序小到大方向的横纵坐标变化
static int []r= {0,-1,1,0};
static int []c= {1,0,0,-1};
static char[][]visited =new char[30][50];
public static void main(String[]args) {
//输入迷宫数据
Scanner sc=new Scanner(System.in) ;
for(int i=0;i<30;i++) {
graph[i]=sc.nextLine().toCharArray();
}
sc.close();
//创建一个 LinkedList 对象 queue,
//用来保存待访问的节点,初始时将起始节点加入队列
LinkedList<Node> queue=new LinkedList<>();
queue.add(new Node(0, 0, ""));
visited[0][0]=1;
String shunxv="";
while(!queue.isEmpty()) {
//从队列中取出并移除队头的元素
//并将其赋值给变量 t
Node t=queue.poll();
int x1=t.x;
int y1=t.y;
String str1=t.str;
if(x1==29&&y1==49) {
shunxv=str1;
break;
}
for(int i=0;i<4;i++){
int x2= x1+c[i];
int y2= y1+r[i];
if(x2>=0&&x2<=29&&y2>=0&&y2<=49&&graph[x2][y2]=='0'&&visited[x2][y2]!=1){
queue.add(new Node(x2, y2, str1+path[i]));
visited[x2][y2]=1;
}
}
}
System.out.println(shunxv);
}
}
蓝桥杯:迷宫
于 2024-04-04 16:22:02 首次发布