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

三、反思与改进

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

相关推荐
SandySY26 分钟前
品三国谈人性
算法·架构
小欣加油34 分钟前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗34 分钟前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗35 分钟前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
DTS小夏39 分钟前
算法社Python基础入门面试题库(新手版·含答案)
python·算法·面试
Mr.Ja1 小时前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器
冷徹 .1 小时前
2024ICPC区域赛香港站
数据结构·c++·算法
浅川.252 小时前
xtuoj string
开发语言·c++·算法
韩非2 小时前
if 语句对程序性能的影响
算法·架构
用户916357440952 小时前
LeetCode热题100——15.三数之和
javascript·算法