uva1600

简单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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值