您的位置:首页 > 其它

蓝桥杯_算法提高_学霸的迷宫(BFS方法)

2016-03-31 09:50 363 查看
问题描述

  学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗。

但学霸为了不要别人打扰,住在一个城堡里,城堡外面是一个二维的格子迷宫,要进城堡必须得先通过迷宫。

因为班长还有妹子要陪,磨刀不误砍柴功,他为了节约时间,从线人那里搞到了迷宫的地图,准备提前计算最短的路线。

可是他现在正向妹子解释这件事情,于是就委托你帮他找一条最短的路线。

输入格式

  第一行两个整数n, m,为迷宫的长宽。

  接下来n行,每行m个数,数之间没有间隔,为0或1中的一个。0表示这个格子可以通过,1表示不可以。

假设你现在已经在迷宫坐标(1,1)的地方,即左上角,迷宫的出口在(n,m)。

每次移动时只能向上下左右4个方向移动到另外一个可以通过的格子里,每次移动算一步。数据保证(1,1),(n,m)可以通过。

输出格式

  第一行一个数为需要的最少步数K。

  第二行K个字符,每个字符∈{U,D,L,R},分别表示上下左右。如果有多条长度相同的最短路径,选择在此表示方法下字典序最小的一个。

样例输入

Input Sample 1:

3 3

001

100

110

Input Sample 2:

3 3

000

000

000

样例输出

Output Sample 1:

4

RDRD

Output Sample 2:

4

DDRR

数据规模和约定

  有20%的数据满足:1<=n,m<=10

  有50%的数据满足:1<=n,m<=50

  有100%的数据满足:1<=n,m<=500。

import java.util.ArrayDeque;
import java.util.Scanner;
public class Main {
private static int n;
private static int m;
private static char[][] mat;
private static ArrayDeque<Node> queue=new ArrayDeque<Node>();
private static boolean[][] hasVisited;
private static String minSteps;
private static  int minStepCount=Integer.MAX_VALUE;
private static boolean isFinished=false;
private static char[] direction={'U','D','R','L'};
private static int[][] dir=new int[][]{{-1,0},{1,0},{0,1},{0,-1}};

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
mat=new char
[m];
hasVisited=new boolean
[m];
for(int i=0;i<n;i++){
mat[i]=sc.next().toCharArray();
}

bfs();

System.out.println(minStepCount);
System.out.println(minSteps);

}

private static void bfs(){
queue.offer(new Node(0,0,"",0));
while(!queue.isEmpty()){
Node node=queue.poll();
hasVisited[node.x][node.y]=true;
if(node.x==n-1&&node.y==m-1){
isFinished=true;
if(minStepCount>node.stepCount){
minStepCount=node.stepCount;
minSteps=node.steps;
}else if(minStepCount==node.stepCount&&minSteps.compareTo(node.steps)>0){
minSteps=node.steps;
}
continue;
}

if(isFinished){
if(node.stepCount>=minStepCount){
continue;
}
}

for(int i=0;i<4;i++){
Node newNode=new Node(node.x+dir[i][0],node.y+dir[i][1],node.steps+direction[i],node.stepCount+1);
if(check(newNode)){
queue.offer(newNode);
}
}

}
}
private static boolean check(Node node){
if(node.x==-1||node.y==-1||node.x==n||node.y==m){
return false;
}else if(hasVisited[node.x][node.y]){
return false;
}else if(mat[node.x][node.y]=='1'){
return false;
}else{
return true;
}
}
}

class Node{
int x;
int y;
String steps;
int stepCount;
public Node(int x,int y,String steps,int stepCount){
this.x=x;
this.y=y;
this.steps=steps;
this.stepCount=stepCount;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: