BFS-迷宫问题-最短路径(Java/C++)

题目

走迷宫问题

Description

给定一个 n×m的二维整数数组,用来表示一个迷宫,数组中只包含 0或 1,其中 0表示可以走的路,1表示不可通过的墙壁。

最初,有一个人位于左上角 (1,1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。

请问,该人从左上角移动至右下角 (n,m)处,至少需要移动多少次。

数据保证 (1,1) 处和 (n,m)处的数字为 0,且一定至少存在一条通路。

Input

第一行包含两个整数 n和 m。

接下来 n行,每行包含 m个整数(0或 1),表示完整的二维数组迷宫。

1 <= n,m<=100

Output

输出一个整数,表示从左上角移动至右下角的最少移动次数。

思路

一个二维数组Maze[][]记录迷宫,另一个二维数组dist[][]记录对应坐标到入口的最短步骤。

宽搜(BFS)能确保找到的是最短路径(最少的移动步数)。

将开始位置的坐标放进队列,并设置入口位置的dist[][]为零。

开始循环,当队列不为空时,执行循环体。

循环体中将队列的第一个元素弹出,并将它的四个方向的坐标来判断,如果满足条件则添加到队列,并将对应坐标到入口的距离+1。

循环执行,直至队列为空。

出口对应的dist[][]即为所求。

C++实现

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

#define MAX 100
int n, m;
int Maze[MAX][MAX];
int dist[MAX][MAX];

int BFS()
{
    queue<pair<int, int>> queue;
    queue.push({ 0, 0 });

    memset(dist, -1, sizeof(dist));
    dist[0][0] = 0;

    int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };

    while (!queue.empty())
    {
        auto temp = queue.front();
        queue.pop();
        for (int i = 0; i < 4; i++)
        {
            int x = temp.first + dx[i], y = temp.second + dy[i];
            if (x >= 0 && x < n && y >= 0 && y < m && Maze[x][y] == 0 && dist[x][y] == -1)
            {
                dist[x][y] = dist[temp.first][temp.second] + 1;
                queue.push({ x, y });
                /*cout << "(" << x << "," << y << ")" << endl;
                cout << "-------------" << endl;*/
            }
        }
    }
    return dist[n - 1][m - 1];

}


int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++) {
            cin >> Maze[i][j];
        } 
    }

    cout << BFS() << endl;
    return 0;
}

java实现

import java.util.LinkedList;
import java.util.Scanner;
public class MazeProblem{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int Maze[][] = new int[n][m]; //迷宫
        int dist[][] = new int[n][m]; //记录该该位置到入口的最短距离

        //迷宫初始化
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                Maze[i][j] = sc.nextInt();
                dist[i][j] = -1;
            }
        }
        int stare[] = new int[]{0,0};//起点坐标
        int directions[][] = new int[][]{{-1,0},{0,1},{1,0},{0,-1}};//四个方向
        dist[0][0] = 0;//起点

        //宽搜(BFS)找到最短路径
        LinkedList<int[]> queue = new LinkedList<>();
        queue.add(stare);
        while(!queue.isEmpty()){
            int temp[] = queue.poll();
            for (int[] direction : directions) {
                int x = temp[0]+direction[0];
                int y = temp[1]+direction[1];
                if(x>=0 && x<n && y>=0 && y<m && Maze[x][y] == 0 && dist[x][y] == -1){
                    dist[x][y] = dist[temp[0]][temp[1]]+1;
                    queue.add(new int[]{x,y});
                    // System.out.println("("+x+","+y+")");
                    // System.out.println("-------------");
                }
                
            }
        }
        System.out.println(dist[n-1][m-1]);
        sc.close();


    }
}

温馨提示:使用java提交算法题时记得将类名改为Main。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
迷宫问题可以使用图论中的最短路径算法来解决,其中比较常用的是广度优先搜索(BFS)或Dijkstra算法。我们可以通过在迷宫中搜索从起点到终点的所有可能路径,并寻找其中最短的路径。 具体实现中,可以将迷宫看作一个二维数组,通过BFS或Dijkstra算法搜索从起点(通常为左上角)到终点(通常为右下角)的最短路径。在搜索过程中,需要记录每个点的距离和是否已经被访问过。 以下是BFS算法Java实现代码: ```java import java.util.*; public class Maze { private static final int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 上右下左四个方向 private int[][] maze; private int rows; private int cols; public Maze(int[][] maze) { this.maze = maze; this.rows = maze.length; this.cols = maze[0].length; } public int shortestPath() { Queue<int[]> queue = new LinkedList<>(); // 存放当前正在遍历的节点 boolean[][] visited = new boolean[rows][cols]; // 记录节点是否已经被遍历过 queue.offer(new int[]{0, 0}); // 将起点放入队列 visited[0][0] = true; int steps = 0; // 记录步数 while (!queue.isEmpty()) { int size = queue.size(); while (size-- > 0) { int[] curr = queue.poll(); // 取出队首节点 if (curr[0] == rows - 1 && curr[1] == cols - 1) { return steps; // 已经到达终点,返回最短路径长度 } for (int[] dir : directions) { int newRow = curr[0] + dir[0]; int newCol = curr[1] + dir[1]; if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && maze[newRow][newCol] == 0 && !visited[newRow][newCol]) { queue.offer(new int[]{newRow, newCol}); // 将新节点加入队列 visited[newRow][newCol] = true; } } } steps++; // BFS遍历完一层,步数+1 } return -1; // 无法到达终点,返回-1 } } ``` 其中,输入的`maze`是一个二维数组,代迷宫,0表示可通过的路径,1表示障碍物。`shortestPath`方法返回从起点到终点的最短路径长度,如果无法到达终点则返回-1。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

motu2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值