AcWing 188. 武士风度的牛
题目描述
题目描述
农民John有很多牛,他想交易其中一头被Don称为The Knight的牛。这头牛有一个独一无二的超能力,在农场里像Knight一样地跳(就是我们熟悉的象棋中马的走法)。
虽然这头神奇的牛不能跳到树上和石头上,但是它可以在牧场上随意跳,我们把牧场用一个x,y的坐标图来表示。
这头神奇的牛像其它牛一样喜欢吃草,给你一张地图,上面标注了The Knight的开始位置,树、灌木、石头以及其它障碍的位置,除此之外还有一捆草。
现在你的任务是,确定The Knight要想吃到草,至少需要跳多少次。
The Knight的位置用’K’来标记,障碍的位置用’*’来标记,草的位置用’H’来标记。
这里有一个地图的例子:
11 | . . . . . . . . . . 10 | . . . . * . . . . . 9 | . . . . . . . . . . 8 | . . . * . * . . . . 7 | . . . . . . . * . . 6 | . . * . . * . . . H 5 | * . . . . . . . . . 4 | . . . * . . . * . . 3 | . K . . . . . . . . 2 | . . . * . . . . . * 1 | . . * . . . . * . . 0 ---------------------- 1 0 1 2 3 4 5 6 7 8 9 0
The Knight 可以按照下图中的A,B,C,D…这条路径用5次跳到草的地方(有可能其它路线的长度也是5):
11 | . . . . . . . . . . 10 | . . . . * . . . . . 9 | . . . . . . . . . . 8 | . . . * . * . . . . 7 | . . . . . . . * . . 6 | . . * . . * . . . F< 5 | * . B . . . . . . . 4 | . . . * C . . * E . 3 | .>A . . . . D . . . 2 | . . . * . . . . . * 1 | . . * . . . . * . . 0 ---------------------- 1 0 1 2 3 4 5 6 7 8 9 0
注意: 数据保证一定有解。
样例
输入样例:10 11 .......... ....*..... .......... ...*.*.... .......*.. ..*..*...H *......... ...*...*.. .K........ ...*.....* ..*....*..
输出样例:
5
bfs 求最短路
分析
使用bfs,第一次搜到的就是最短路
注意每个点可以走八个方向
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 160;
char g[N][N];
bool st[N][N];
int dist[N][N];
int c, r;
int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2}, dy[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int bfs(int a, int b)
{
memset(dist, -1, sizeof dist);
queue<PII> q;
q.push({a, b});
dist[a][b] = 0;
st[a][b] = true;
while(!q.empty())
{
PII tmp = q.front();
q.pop();
int x = tmp.first, y = tmp.second;
for(int i = 0; i < 8; i++)
{
int nx = x + dx[i], ny = y + dy[i];
if(nx >= 1 && nx <= r && ny >=1 && ny <= c && !st[nx][ny] && g[nx][ny] != '*')
{
st[nx][ny] = true;
dist[nx][ny] = dist[x][y] + 1;
if(g[nx][ny] == 'H') return dist[nx][ny];
q.push({nx, ny}); // .
}
}
}
}
int main()
{
int sx, sy;
scanf("%d%d", &c, &r);
getchar();
for(int i = 1; i <= r; i++)
{
for(int j = 1; j <= c; j++)
{
char c = getchar();
g[i][j] = c;
if(c == 'K') sx = i, sy = j;
}
getchar();
}
int res = bfs(sx, sy);
printf("%d\n", res);
return 0;
}