HJ156 走迷宫

  • 题目
  • 题解(95)
  • 讨论(34)
  • 排行

简单 通过率:33.65% 时间限制:3秒 空间限制:256M

知识点广度优先搜索(BFS)

校招时部分企业笔试将禁止编程题跳出页面,为提前适应,练习时请使用在线自测,而非本地IDE。

描述

给定一个 n×mn×m 的网格。你从起点 (xs,ys)(xs​,ys​) 出发,每一次可以向上、下、左、右移动一步(若不超出边界)。某些格子上存在障碍物,无法经过。求从 (xs,ys)(xs​,ys​) 移动到终点 (xt,yt)(xt​,yt​) 的最少步数;若无法到达,输出 −1−1。

输入描述:

在一行上输入两个整数 n,m(1≦n,m≦1000)n,m(1≦n,m≦1000),代表网格的行数与列数。

在一行上输入四个整数 xs,ys,xt,yt(1≦xs,xt≦n; 1≦ys,yt≦m)xs​,ys​,xt​,yt​(1≦xs​,xt​≦n; 1≦ys​,yt​≦m),代表起点与终点的坐标。

此后 nn 行,第 ii 行输入一个长度为 mm 的字符串 gigi​,其中

∙ ∙若 gi,j="*"gi,j​="*",表示第 ii 行第 jj 列为障碍物;

∙ ∙若 gi,j="."gi,j​=".",表示该格子可通行。

保证起点所在格子可通行。

输出描述:

输出一个整数,表示最少移动次数;若无法到达,输出 −1−1。

示例1

输入:

复制代码
5 5
1 1 5 5
.....
****.
.....
**.**
.....

复制输出:

复制代码
12

复制

示例2

输入:

复制代码
5 5
1 1 4 5
.....
****.
.....
**.**
.....

复制输出:

复制代码
-1

复制

示例3

输入:

复制代码
5 5
1 1 5 5
.....
****.
.....
*****
.....

复制输出:

复制代码
-1
cpp 复制代码
#include<iostream>
#include<vector>
#include<queue>
#define INF 1e+7
using namespace std;
typedef struct node {
    int row;
    int col;
    node(int f, int t) :row(f), col(t) {}
}Node;
typedef struct direct {
    int crow;
    int ccol;
    direct(int f, int t) :crow(f), ccol (t) {}
}Direct;
vector<char> vec[1001];
int dp[1001][1001];
Direct dir[4] = { Direct {1,0},Direct{-1,0},Direct{0,1},Direct{0,-1} };
int main()
{
    char c;
    int xs, ys, n, m, xt, yt;
    queue<Node> qu;
    cin >> n >> m;
    cin >> xs >> ys >> xt >> yt;
    for (int i = 0; i <= n; ++i) {
        for (int j = 0; j <= m; ++j)
            dp[i][j] = -1;
    }
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            cin >> c;
            if (vec[i].empty())
                vec[i].push_back('0');
            vec[i].push_back(c);
        }
    }
    qu.push(Node{ xs,ys });
    while (!qu.empty()) {
        Node point = qu.front();
        qu.pop();
        for (int i = 0; i < 4; ++i) {
            int row = point.row + dir[i].crow;
            int col = point.col + dir[i].ccol;
            if (row >= 1 && row <= n && col >= 1 && col <= m && vec[row][col] == '.' && dp[row][col] == -1) {
                qu.push(Node{ row,col });
                dp[row][col] = dp[point.row][point.col] + 1;
            }
        }
    }
    if (dp[xt][yt] != -1)
        cout << ((xt == xs && yt == ys ) ? 0 : dp[xt][yt] + 1);
    else
        cout << -1;
}
相关推荐
三毛的二哥7 小时前
BEV:典型BEV算法总结
人工智能·算法·计算机视觉·3d
南宫萧幕8 小时前
自控PID+MATLAB仿真+混动P0/P1/P2/P3/P4构型
算法·机器学习·matlab·simulink·控制·pid
浪浪小洋9 小时前
c++ qt课设定制
开发语言·c++
charlie1145141919 小时前
嵌入式C++工程实践第16篇:第四次重构 —— LED模板,从通用GPIO到专用抽象
c语言·开发语言·c++·驱动开发·嵌入式硬件·重构
handler019 小时前
Linux: 基本指令知识点(2)
linux·服务器·c语言·c++·笔记·学习
故事和你919 小时前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
我叫黑大帅9 小时前
为什么map查找时间复杂度是O(1)?
后端·算法·面试
炽烈小老头9 小时前
【每天学习一点算法 2026/04/20】除自身以外数组的乘积
学习·算法
skilllite作者10 小时前
AI agent 的 Assistant Auto LLM Routing 规划的思考
网络·人工智能·算法·rust·openclaw·agentskills
香蕉鼠片11 小时前
MFC是什么
c++·mfc