【蓝桥杯】走迷宫

题目:

解题思路:

简单的广度优先算法(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;
  }
}
相关推荐
yoi啃码磕了牙3 分钟前
Unity—Localization 多语言
java·数据库·mysql
跟着珅聪学java4 分钟前
在Java中判断Word文档中是否包含表格并读取表格内容,可以使用Apache POI库教程
java·开发语言·word
柳鲲鹏27 分钟前
RGB转换为NV12,查表式算法
linux·c语言·算法
橘颂TA27 分钟前
【剑斩OFFER】算法的暴力美学——串联所有单词的字串
数据结构·算法·c/c++
Kuo-Teng27 分钟前
LeetCode 73: Set Matrix Zeroes
java·算法·leetcode·职场和发展
王元_SmallA30 分钟前
服务器公网IP、私网IP、弹性IP是什么?区别与应
java·后端
mit6.82430 分钟前
[HDiffPatch] 补丁算法 | `patch_decompress_with_cache` | `getStreamClip` | RLE游程编码
c++·算法
程序猿202331 分钟前
Python每日一练---第六天:罗马数字转整数
开发语言·python·算法
葵续浅笑1 小时前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode
装不满的克莱因瓶1 小时前
【Java架构师】各个微服务之间有哪些调用方式?
java·开发语言·微服务·架构·dubbo·restful·springcloud