蓝桥杯 算法提高 学霸的迷宫 JAVA

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

class Main {
	
    public static void main(String[] args) throws IOException   {
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	String s[] = br.readLine().split(" ");
    	int n = Integer.parseInt(s[0]);
    	int m = Integer.parseInt(s[1]);
    	char c[][] = new char[n][m];
    	for (int i = 0; i <n; i++) {
			c[i] = br.readLine().toCharArray();
		}
    	boolean b[][] = new boolean[n][m];
    	b[0][0] = true;
    	LinkedList<Node>  list = new LinkedList<>();
    	list.add(new Node(0,0,'.',null));
    	while(!list.isEmpty()){
    		Node temp = list.removeFirst();
    		int x = temp.x;
    		int y = temp.y;
    		if(x== n-1 && y== m-1){
    			int i = 0;
    			StringBuilder sb = new StringBuilder();
    			while(temp.node!= null){
    				i++;
    				sb.insert(0,temp.c);
    				temp = temp.node;
    			}
    			System.out.println(i);
    			System.out.println(sb.toString());
    			return;
    		}
    		
    		if(x+1<n && c[x+1][y] =='0' && !b[x+1][y]){
    			list.addLast(new Node(x+1,y,'D',temp));
    			if(x+1 != n-1 || y != m-1){
    				b[x+1][y] = true;
    			}
    		}
    		
    		if(y-1 >=0 && c[x][y-1] == '0' && !b[x][y-1]){
    			list.addLast(new Node(x,y-1,'L',temp));
    			if(x != n-1 || y-1 != m-1){
    				b[x][y-1] =true;
    			}
    		}
    		
    		
    		
    		if(y+1<m && c[x][y+1] =='0' && !b[x][y+1]){
    			list.addLast(new Node(x,y+1,'R',temp));
    			if(x != n-1 || y+1 != m-1){
    				b[x][y+1] = true;
    			}
    		}
    		
    		if(x-1>=0 && c[x-1][y] =='0'&& !b[x-1][y]){
    			list.addLast(new Node(x-1,y,'U',temp));
    			if(x-1 != n-1 || y != m-1){
    				b[x-1][y] = true;
    			}
    		}
    	
    	}
    	
	}

	
}
class Node{
	int x;
	int y;
	char c;
	Node node;
	public Node(int x, int y, char c, Node node) {
		super();
		this.x = x;
		this.y = y;
		this.c = c;
		this.node = node;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值