【蓝桥杯】走迷宫

题目:

解题思路:

简单的广度优先算法(BFS)

BFS 的特性

  1. 按层次遍历:BFS 按照节点的距离(边的数量)来逐层访问节点。
  2. 保证最短路径:对于无权图(所有边权重相同),BFS 能够找到从起点到任何其他节点的最短路径。
  3. 避免回路:通过使用已访问标记(visited 数组),可以防止重复访问同一个节点,从而避免无限循环。
  4. 队列结构:使用队列来管理待访问的节点。
java 复制代码
import java.util.Scanner;
import java.util.Queue;
import java.util.ArrayDeque;
// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {
  //方向
  static int[] dx = {0, 0, -1, 1};
  static int[] dy = {1, -1, 0, 0};
  //标记是否走过
  static boolean[][] visted;
  //矩阵大小
  static int N, M;
  //入口、出口位置
  static int startx, starty, endx, endy; 
  public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      //在此输入您的代码...
      N = scan.nextInt();
      M = scan.nextInt();
      int [][] arr = new int[N][M];
      visted = new boolean[N][M];
      for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
          arr[i][j] = scan.nextInt(); 
        }
      }
      startx = scan.nextInt();
      starty = scan.nextInt();
      endx = scan.nextInt();
      endy = scan.nextInt();
      System.out.println(bfs(arr, startx - 1, starty - 1));
      scan.close();
  }
  public static int bfs(int[][] arr, int x, int y) {
    //创建队列,更新位置
    Queue<int[]> q = new ArrayDeque<>();
    q.offer(new int[] {x, y, 0});

    while(!q.isEmpty()) {
      int[] poll = q.poll();
      int x1 = poll[0];
      int y1 = poll[1];
      int steps = poll[2];
      //判断是否到达终点
      if (x1 == endx-1 && y1 == endy-1) {
        return steps;
      }
      //根据四个方向走下一步
      for (int i = 0; i < 4; i++) {
        int xx = x1 + dx[i];
        int yy = y1 + dy[i];
        if (xx >=0 && yy >= 0 && xx < N && yy < M && !visted[xx][yy] && arr[xx][yy] == 1) {
          visted[xx][yy] = true;
          q.offer(new int[] {xx, yy, steps + 1});
        }
      }
    }
    return -1;
  }
}
相关推荐
爱喝一杯白开水13 分钟前
SpringMVC从入门到上手-全面讲解SpringMVC的使用.
java·spring·springmvc
王景程22 分钟前
如何测试短信接口
java·服务器·前端
2301_8076114929 分钟前
77. 组合
c++·算法·leetcode·深度优先·回溯
zhang23839061541 小时前
IDEA add gitlab account 提示
java·gitlab·intellij-idea·idea
牛马baby2 小时前
Java高频面试之并发编程-07
java·开发语言·面试
SsummerC2 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
卓怡学长2 小时前
w304基于HTML5的民谣网站的设计与实现
java·前端·数据库·spring boot·spring·html5
YONG823_API2 小时前
深度探究获取淘宝商品数据的途径|API接口|批量自动化采集商品数据
java·前端·自动化
yzhSWJ2 小时前
Spring Boot中自定义404异常处理问题学习笔记
java·javascript
盖世英雄酱581362 小时前
分布式ID所有生成方案
java·后端