题275.bfs最短路-acwing-Q188--武士风度的牛


题275.bfs最短路-acwing-Q188–武士风度的牛


一、题目

在这里插入图片描述
在这里插入图片描述

二、题解

套bfs最短路模板就好

#include <bits/stdc++.h>

#define x first
#define y second

using namespace std;

typedef pair<int,int> pii;
const int maxn=201;
const int dx[]={-2,-1,1,2,2,1,-1,-2};//定义扩展方向数组
const int dy[]={1,2,2,1,-1,-2,-2,-1};

int R,C;
char G[maxn][maxn];
int dist[maxn][maxn];//记录源点到(i,j)的最短距离

int bfs(int sx,int sy)
{
    fill(dist[0],dist[0]+maxn*maxn,-1);
    queue<pii> q;
    q.push({sx,sy});
    dist[sx][sy]=0;
    while(!q.empty())
    {
        pii tmp=q.front();
        q.pop();
        for(int i=0;i<8;i++)//向八个方向扩展
        {
            int nx=tmp.x+dx[i];
            int ny=tmp.y+dy[i];
            if(nx<0||nx>=R||ny<0||ny>=C)//超范围
            {
                continue;
            }
            if(G[nx][ny]=='*')//不可达
            {
                continue;
            }
            if(dist[nx][ny]!=-1)//已确定最短距离
            {
                continue;
            }
            if(G[nx][ny]=='H')//到达终点
            {
                return dist[nx][ny]=dist[tmp.x][tmp.y]+1;
            }
            dist[nx][ny]=dist[tmp.x][tmp.y]+1;
            q.push({nx,ny});
        }
    }
    return -1;
}

int main()
{
    cin>>C>>R;
    int sx,sy;
    for(int i=0;i<R;i++)
    {
        for(int j=0;j<C;j++)
        {
            cin>>G[i][j];
            if(G[i][j]=='K')
            {
                sx=i,sy=j;
            }
        }
    }
    cout<<bfs(sx,sy);
}

在这里插入图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值