搜索的时候加一点剪枝就ok,另外学习一下这种开数组的方法,这样不会MLE!
#include <iostream>
#include <cmath>
#include <set>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <queue>
#include <vector>
#define IO \
ios::sync_with_stdio(false); \
// cout.tie(0);
#define lson(x) node << 1, start, mid
#define rson(x) node << 1 | 1, mid + 1, end
using namespace std;
// int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> P;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const int maxn = 1e6 + 10;
const int maxm = 1e4 + 10;
const LL mod = 998244353;
const double eps = 1e-8;
const double pi = acos(-1);
int dis[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};
// int m[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int n, m, k;
int sx, sy, fx, fy;
vector<string> s(maxn);
bool check(int x, int y)
{
if (x >= 0 && x < n && y >= 0 && y < m && s[x][y] != '@')
return true;
return false;
}
int main()
{
#ifdef WXY
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
cin >> n >> m >> k;
cin >> sx >> sy >> fx >> fy;
--sx, --sy, --fx, --fy;
for (int i = 0; i < n; i++)
{
cin >> s[i];
}
vector<vector<int>> a(n + 10, vector<int>(m + 10, inf));// 这样开二维数组不会炸内存
queue<P> q;
a[sx][sy] = 0;
q.push(make_pair(sx, sy));
while (!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int t = a[x][y] + 1;
int tx = x, ty = y;
for (int j = 1; j <= k; j++)
{
tx += dis[i][0];
ty += dis[i][1];
if (!check(tx, ty) || a[tx][ty] < t)// 剪枝
break;
if (a[tx][ty] > t)
{
a[tx][ty] = t;
q.push(make_pair(tx, ty));
}
}
}
}
if (a[fx][fy] == inf)
cout << "-1";
else
cout << a[fx][fy];
return 0;
}