牛客月赛:走出迷宫(Java)

题目

链接:走出迷宫
来源:牛客网

小明现在在玩一个游戏,游戏来到了教学关卡,迷宫是一个N*M的矩阵。
小明的起点在地图中用“S”来表示,终点用“E”来表示,障碍物用“#”来表示,空地用“.”来表示。
障碍物不能通过。小明如果现在在点(x,y)处,那么下一步只能走到相邻的四个格子中的某一个:(x+1,y),(x-1,y),(x,y+1),(x,y-1);
小明想要知道,现在他能否从起点走到终点。

输入描述

本题包含多组数据。
每组数据先输入两个数字N,M
接下来N行,每行M个字符,表示地图的状态。
数据范围:
2<=N,M<=500
保证有一个起点S,同时保证有一个终点E.

输出描述

每组数据输出一行,如果小明能够从起点走到终点,那么输出Yes,否则输出No

思路

用广度优先搜索

  • 把字符串转为字符数组方便搜索
  • 先把起点位置入队列,标记为死路
  • 从起点位置搜索当前位置的上下左右,只要搜索过就标记为死路
  • 到达终点就标记一下,跳出循环

代码

import java.util.*;
class Node {
    
    
    int x;
    int y;
    
    public Node(int x, int y) {
    
    
        this.x = x;
        this.y = y;
    }
}
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        // 处理多组输入
        while (sc.hasNext()) {
    
    
            int n = sc.nextInt();
            int m = sc.nextInt();
            char[][] ch = new char[n][m];

            for (int i = 0 ; i < n; i++) {
    
    
                ch[i] = sc.next().toCharArray();
            }
            Queue<Node> queue = new LinkedList<>();
            for (int i = 0; i < n; i++) {
    
    
                for (int j = 0; j < m; j++) {
    
    
                    char c = ch[i][j];
                    if (c == 'S') {
    
    
                        queue.offer(new Node(i,j));
                        ch[i][j] = '#';
                        break;
                        
                    }
                }
            }
            // 上下左右
            int[][] upDownLeftRight = {
    
    {
    
    -1,0},{
    
    1,0},{
    
    0,-1},{
    
    0,1}};
            boolean flag = false;
            while (!queue.isEmpty()) {
    
    
                for (int i = 0; i < 4; i++) {
    
    
                    int newX = queue.peek().x + upDownLeftRight[i][0];
                    int newY = queue.peek().y + upDownLeftRight[i][1];
                    if (newX < 0 || newX >= n || newY < 0 || newY >= m || ch[newX][newY] == '#') {
    
    
                        continue;
                    }
                    if (ch[newX][newY] == 'E') {
    
    
                        flag = true;
                        break;
                    }
                    queue.offer(new Node(newX,newY));
                    ch[newX][newY] = '#';
                }
                queue.poll();
                if (flag) {
    
    
                    break;
                }
            }
            if (flag) {
    
    
                System.out.println("Yes");
            } else {
    
    
                System.out.println("No");
            }
        }
    } 
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_53946852/article/details/124910266