【AcWing】188. 武士风度的牛

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

思路:简单bfs。

#include 
#include 
#include 
#include 
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;
}

你可能感兴趣的:(算法,算法,bfs)