简单BFS,第一次忘了用vis数组判重,TLE,第二次vis数组只用了二维,忘了加上障碍物的个数这一维,导致WA,第3次AC
# include <cstdio>
# include <cstring>
# include <iostream>
# include <algorithm>
# include <queue>
using namespace std;
const int maxn = 20 + 5;
int maps[maxn][maxn];
int vis[maxn][maxn][maxn];
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int best;
struct Node {
int x, y, dist, cnt;
Node() : x(0), y(0), dist(0), cnt(0) { }
Node(int xx, int yy) : x(xx), y(yy) { }
};
bool bfs(int, int, int);
int main(void)
{
int T, m, n, k;
scanf("%d", &T);
while (T-- && scanf("%d %d %d", &m, &n, &k)) {
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
scanf("%d", &maps[i][j]);
best = 0;
bool ok = bfs(m, n, k);
if (ok) printf("%d\n", best);
else printf("-1\n");
}
return 0;
}
bool bfs(int m, int n, int k) {
memset(vis, 0, sizeof vis);
queue<Node> q;
Node start(0, 0);
start.dist = 0; start.cnt = 0;
q.push(start);
while (!q.empty()) {
Node u = q.front(); q.pop();
if (u.x == m - 1 && u.y == n - 1) { best = u.dist; return true; }
for (int i = 0; i < 4; ++i) {
int newx = u.x + dx[i];
int newy = u.y + dy[i];
if (newx < 0 || newx >= m || newy < 0 || newy >= n) continue;
int cnt = 0;
if (maps[newx][newy]) cnt = u.cnt + 1;
if (cnt > k) continue;
if (vis[newx][newy][cnt]) continue;
else vis[newx][newy][cnt] = 1;
Node v(newx, newy);
v.dist = u.dist + 1; v.cnt = cnt;
q.push(v);
}
}
return false;
}