题目描述
https://www.acwing.com/problem/content/190/
样例
输入样例:
10 11
..........
....*.....
..........
...*.*....
.......*..
..*..*...H
*.........
...*...*..
.K........
...*.....*
..*....*..
输出样例:
5
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 160;
typedef pair<int, int> PII;
int n, m;
char g[N][N];
int dx[] = {-2, -2, +2, +2, -1, -1, +1, +1}, dy[] = {-1, +1, -1, +1, -2, +2, -2, +2};
PII start, en;
int dist[N][N];
void bfs(int x, int y)
{
queue<PII> q;
q.push({x, y});
dist[x][y] = 0;
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 8 ; i ++ )
{
int a = t.first + dx[i], b = t.second + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (g[a][b] == '*') continue;
if (dist[a][b] != -1) continue;
dist[a][b] = dist[t.first][t.second] + 1;
q.push({a, b});
if (g[a][b] == 'H') cout << dist[a][b] <<endl;//注意优化
}
}
}
int main()
{
cin >> m >> n;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
{
cin >> g[i][j];
if (g[i][j] == 'K') start = {i, j};
if (g[i][j] == 'H') en = {i, j};
}
memset(dist, -1, sizeof(dist));
bfs(start.first, start.second);
cout << dist[en.first][en.second] << endl;
return 0;
}