【错题集-编程题】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;
}

三、反思与改进

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

相关推荐
荆棘鸟智能5 分钟前
虫情测报灯图像识别算法实践:小目标检测、粘连计数与飞虱细粒度分类
算法·目标检测·分类
爱读书的小胖27 分钟前
LeetCode 27. 移除元素(C)解题分析
数据结构·算法
科技小E28 分钟前
敏感数据不敢上云训练?本地大模型推理服务器DLTM私有化部署,让训练全程留在企业内网
大数据·算法·自动化
小草cys1 小时前
用 GPT 直接生成可编辑 PPTX 的实操记录,artifact-tool是OpenAICodex环境专用
gpt·算法·pptx
爱读书的小胖1 小时前
Codewars: A Brave New Wordle(C)解题分析
c语言·数据结构·算法
Escalating_xu1 小时前
【数据结构】顺序表的应用:动态通讯录项目与双指针经典算法
c语言·数据结构·算法
其实防守也摸鱼1 小时前
CTF Web 6 题全解 Writeup
linux·sql·学习·算法·安全·ctf·xss
宇明一不急1 小时前
string和byte的相互转换
算法
波力海苔夹心脆6751 小时前
VisionPro 与 VisionMaster 对比(上):软件定位、开发环境与核心视觉工具对照
图像处理·算法·计算机视觉·c#·视觉检测·个人开发·vp9
动词ing2 小时前
【题目练习】盛最多水的容器
算法·目标检测