AcWing 188. 武士风度的牛(最少步数)

题目链接:点击这里
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
d [ N ] [ N ] d[N][N] 数组记录最小步数,初始化为 1 -1 顺便用来判重。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>

#define x first 
#define y second

using namespace std;
typedef pair<int,int> PII;
const int N = 160, M = N * N;

int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int dy[8] = {-2, -1, 1, 2, 2, 1, -1, -2};

int n, m;
char g[N][N];
int d[N][N];
PII q[M];

int bfs()
{
    int sx, sy;
    for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
            if(g[i][j] == 'K')
                sx = i, sy = j;
    
    int hh = 0, tt = -1;
    memset(d, -1, sizeof d);
    
    q[++tt] = {sx, sy};
    d[sx][sy] = 0;
    
    while(hh <= tt)
    {
        PII t = q[hh++];
        
        for(int i = 0; i < 8; ++i)
        {
            int nx = t.x + dx[i], ny = t.y + dy[i];
            if(nx < 0 || nx >= n || ny < 0 || ny >= m)  continue;
            if(g[nx][ny] == '*')    continue;
            if(d[nx][ny] != -1) continue;
            
            q[++tt] = {nx, ny};
            d[nx][ny] = d[t.x][t.y] + 1;
            
            if(g[nx][ny] == 'H')    return d[nx][ny];
        }
    }
}

int main()
{
    scanf("%d%d", &m, &n);      // n行m列
    
    for(int i = 0; i < n; ++i)  scanf("%s", g[i]);
    
    printf("%d\n", bfs());
    
    return 0;
}
发布了844 篇原创文章 · 获赞 135 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/105065980