【AcWing】188. 武士风度的牛

该篇博客介绍了一个简单的BFS(广度优先搜索)算法应用实例,用于解决从起点(K)到终点(H)的最短路径问题。在给定的二维矩阵迷宫中,通过BFS遍历找到从起点到终点的最短步数,并输出结果。代码中定义了BFS函数,用队列实现节点的遍历,并更新路径长度。

https://www.acwing.com/problem/content/190/

思路:简单bfs。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int maxn = 233;

typedef struct
{
    int x, y;
}P;

int n, m;
char a[maxn][maxn];
int ans[maxn][maxn];
int dx[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};

void bfs(int x, int y)
{
    queue<P> q;
    q.push({x, y});
    a[x][y] = '*';
    ans[x][y] = 0;
    int flag = 0;
    
    while(q.size())
    {
        P t = q.front();
        q.pop();
        
        for(int i = 0;i < 8; i++)
        {
            int xx = t.x + dx[i];
            int yy = t.y + dy[i];
            if(xx < 1 || xx > n || yy < 1 || yy > m) continue;
            if(a[xx][yy] != '*')
            {
                ans[xx][yy] = ans[t.x][t.y] + 1;
                if(a[xx][yy] == 'H')
                {
                    printf("%d\n", ans[xx][yy]);
                    flag = 1;
                    break;
                }
                a[xx][yy] = '*';
                q.push({xx, yy});
            }
        }
        
        if(flag) break;
    }
    
}

int main()
{
    scanf("%d%d", &m, &n);
    for(int i = 1;i <= n; i++)
        scanf("%s", a[i] + 1);
    
    for(int i = 1;i <= n; i++)
    {
        for(int j = 1;j <= m; j++)
        {
            if(a[i][j] == 'K')
            {
                bfs(i, j);
                break;
            }
        }
    }
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值