AcWing 1101. 献给阿尔吉侬的花束 解题思路及代码

先贴个题目:

以及原题链接: 1101. 献给阿尔吉侬的花束 - AcWing题库icon-default.png?t=N7T8https://www.acwing.com/problem/content/1103/

 一道很经典很裸的bfs模板题,简单提一句bfs是啥吧,感觉大家应该都知道,bfs(广度优先搜索)指从根节点开始,每次扩展遍历从当前节点能往前走一步就到达的节点(且没被走过),从而遍历整个图,实现的话一般是用队列实现的。如果不了解的话可以单独去搜搜bfs是啥,这里不过多赘述。

代码如下:

#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 210;

int r, c;
int dx[4] = {0, 0, 1, -1}, dy[4] = {-1, 1, 0, 0};
int dis[N][N];
char map[N][N];

int bfs(PII start, PII end)
{
    queue<PII> q;
    q.push(start);
    dis[start.x][start.y] = 0;
    while (q.size())
    {
        PII tmp = q.front();
        q.pop();
        if (tmp == end)
        {
            return dis[end.x][end.y];
        }
        for (int i = 0; i < 4; ++i)
        {
            int tx = tmp.x + dx[i], ty = tmp.y + dy[i];
            if (tx < 0 || tx >= r || ty < 0 || ty >= c)
                continue;
            if (map[tx][ty]!='#' && dis[tx][ty] == -1)
            {
                dis[tx][ty] = dis[tmp.x][tmp.y] + 1;
                q.push(make_pair(tx, ty));
            }
        }
    }
    return -1;
}

int main()
{
    int t;
    cin >> t;
    PII start, end;
    while (t--)
    {
        memset(dis, -1, sizeof(dis));
        cin >> r >> c;
        for (int i = 0; i < r; ++i)
        {
            getchar();
            for (int j = 0; j < c; ++j)
            {
                scanf("%c", &map[i][j]);
                if (map[i][j] == 'S')
                {
                    start = make_pair(i, j);
                }
                else if (map[i][j] == 'E')
                {
                    end = make_pair(i, j);
                }
            }
        }
        int ans = bfs(start, end);
        if (ans == -1)
            cout << "oop!" << endl;
        else
            cout << ans << endl;
    }
}

挺裸的板子题,做的挺爽的,一遍就ac了。

by————2024.3.16刷题记录

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值