蓝桥杯:迷宫

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);
 
 }
 }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值