【思特奇杯·云上蓝桥-算法集训营】第2周 05-迷宫

05-迷宫

题目描述

下图给出了一个迷宫的平面图,其中标记为 1 的为障碍,标记为 0 的为可 以通行的地方。

010000

000100

001001

110000

迷宫的入口为左上角,出口为右下角,在迷宫中,只能从一个位置走到这 个它的上、下、左、右四个方向之一。 对于上面的迷宫,从入口开始,可以按DRRURRDDDR 的顺序通过迷宫, 一共 10 步。其中 D、U、L、R 分别表示向下、向上、向左、向右走。 对于下面这个更复杂的迷宫(30 行 50 列),请找出一种通过迷宫的方式, 其使用的步数最少,在步数最少的前提下,请找出字典序最小的一个作为答案。 请注意在字典序中D<L<R<U。(如果你把以下文字复制到文本文件中,请务 必检查复制的内容是否与文档中的一致。在试题目录下有一个文件 maze.txt, 内容与下面的文本相同)

答案提交

这是一道结果填空的题,你只需要算出结果后提交即可。本题的结果为一 个字符串,包含四种字母 D、U、L、R,在提交答案时只填写这个字符串,填 写多余的内容将无法得分



使用BFS求解

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class code05_maze {
    static int[] row = { 1, 0, 0, -1 };
    static int[] col = { 0, -1, 1, 0 };
    static String[] dir = { "D", "L", "R", "U" };
    static boolean[][] visited  = new boolean[4][6];
    static char[][] arr = {
            {'0','1','0','0','0','0'},
            {'0','0','0','1','0','0'},
            {'0','0','1','0','0','1'},
            {'1','1','0','0','0','0'}
    };
    static  int n,m;
    static char[][] target = new char[n][m];

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        for(int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                target[i][j] = sc.next().charAt(0);
            }
        }
        leastStep();
    }
    public static void leastStep(){
        Queue<Node> queue = new LinkedList<>();
        queue.add(new Node(0,0,0,""));
        while(!queue.isEmpty()){
            Node cur = queue.poll();
            visited[cur.x][cur.y] = true;
            //base case
            if(cur.x==n-1 && cur.y==m-1){
                System.out.println(cur.path);
                return;
            }
            for(int i=0;i<4;i++){
                int newX = cur.x + row[i];
                int newY = cur.y + col[i];
                if(check(newX,newY)){
                    Node node1 = new Node(newX,newY, cur.step+1, cur.path+dir[i]);
                    queue.add(node1);
                }
            }
        }
    }
    public static boolean check(int i,int j){
        if(i<0||j<0||i>=n||j>=m){
            return false;
        }
        if(visited[i][j] || arr[i][j]=='1'){
            return false;
        }
        return true;
    }

}
class Node{
    int x;
    int y;
    int step;//步数
    String path;//路径

    public Node(int x, int y, int step, String path) {
        this.x = x;
        this.y = y;
        this.step = step;
        this.path = path;
    }
}

运行结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值