【错题集-编程题】kotori 和迷宫(BFS / DFS)

牛客对应题目链接:kotori和迷宫 (nowcoder.com)


一、分析题目

迷宫问题的扩展。


二、代码

cpp 复制代码
#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

const int N = 35;
int x1, y1; // 标记起点位置
int n, m;
char arr[N][N];
int dist[N][N];
queue<pair<int, int>> q;

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

void bfs()
{
    memset(dist, -1, sizeof dist);
    dist[x1][y1] = 0;
    q.push({x1, y1});
 
    while(q.size())
    {
        auto [x2, y2] = q.front();
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            int a = x2 + dx[i], b = y2 + dy[i];
            if(a >= 1 && a <= n && b >= 1 && b <= m && dist[a][b] == -1 && arr[a][b] != '*')
            {
                dist[a][b] = dist[x2][y2] + 1;
                if(arr[a][b] != 'e')
                {
                    q.push({a, b});
                }
            }
        }
    }
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
        {
            cin >> arr[i][j];
            if(arr[i][j] == 'k')
            {
                x1 = i, y1 = j;
            }
        }
    }
 
    bfs();
 
    int count = 0, ret = 1e9;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
        {
            if(arr[i][j] == 'e' && dist[i][j] != -1)
            {
                count++;
                ret = min(ret, dist[i][j]);
            }
        }
    }
    if(count == 0) cout << -1 << endl;
    else cout << count << " " << ret << endl;
 
    return 0;
}

三、反思与改进

没有设置好对不同字符的处理条件。

相关推荐
旖-旎24 分钟前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC1 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn2 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹2 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术2 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber5 小时前
检索技术的实际应用
人工智能·算法
hhzz6 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_6 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI7 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅