题目链接: https://vjudge.net/problem/UVA-1600
思路
开了一个二维数组buf
记录图的信息。
Node
中额外开了一片内存用来储存穿墙信息。
这道题一定要注意将点标记为visited
的位置。
第一次提交将语句写在了下方代码现在注释掉的位置,这样是不对的,例如下面这组数据
1
12 20
2
0 1 1 1 0 1 1 0 0 1 1 1 0 1 1 0 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
0 1 1 0 0 1 1 1 0 1 1 0 0 1 1 1 0 1 1 0
可以自己跑一下看看错误发生在哪。
代码
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <utility>
using namespace std;
int buf[50][50];
int vis[50][50];
int r, c, k;
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
struct Node
{
int x;
int y;
int b;
int dis;
Node(int x, int y, int b, int dis) :x(x), y(y), b(b), dis(dis) {};
};
void bfs()
{
memset(vis, 0, sizeof(vis));
queue<Node> q;
q.push({ 0, 0, 0, 0 });
vis[0][0] = 1;
while (!q.empty()) {
Node u = q.front(); q.pop();
if (u.x == r - 1 && u.y == c - 1) {
printf("%d\n", u.dis);
return;
}
vis[u.x][u.y] = 1;
for (int i = 0; i < 4; i++) {
int next_b = buf[u.x + dx[i]][u.y + dy[i]] ? u.b + 1 : 0;
Node next(u.x + dx[i], u.y + dy[i], next_b, u.dis + 1);
if (next.x >= 0 && next.x < r && next.y >= 0 && next.y < c && !vis[next.x][next.y] && next.b <= k) {
q.push(next);
//vis[u.x + dx[i]][u.y + dy[i]] = 1;
}
}
}
printf("-1\n");
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int t; cin >> t;
while (t--) {
cin >> r >> c >> k;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
scanf("%d", &buf[i][j]);
}
}
bfs();
}
return 0;
}