题目链接: D. Olya and Energy Drinks
题目大意
一个n*m的迷宫,
思路
最普通的BFS, 但复杂度
代码
GNU C++14 Accepted 1747 ms 13600 KB
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 1e3 + 10;
int n, m, k, d[maxn][maxn];
int x_1, x_2, y_1, y_2;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
char s[maxn][maxn];
typedef pair<int, int> P;
int main()
{
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < n; ++i) scanf("%s", s[i]);
scanf("%d%d%d%d", &x_1, &y_1, &x_2, &y_2);
if(x_1 == x_2 && y_1 == y_2)
{
cout << 0 << endl;
return 0;
}
--x_1, --x_2, --y_1, --y_2;
memset(d, -1, sizeof(d));
d[x_1][y_1] = 0;
queue<P> que;
que.push(P(x_1, y_1));
while (!que.empty())
{
P now = que.front(); que.pop();
for (int i = 0; i < 4; ++i)
{
for (int a = 1; a <= k; ++a)
{
int nx = now.first + dx[i] * a;
int ny = now.second + dy[i] * a;
if (0 <= nx && nx < n && 0 <= ny && ny < m && d[nx][ny] == -1 && s[nx][ny] == '.')
{
d[nx][ny] = d[now.first][now.second] + 1;
que.push(P(nx, ny));
if (nx == x_2 && ny == y_2)
{
cout << d[x_2][y_2] << endl;
return 0;
}
}
else if (nx < 0 || nx >= n || ny < 0 || ny >= m || s[nx][ny] == '#') break;
}
}
}
cout << -1 << endl;
return 0;
}