CCF CSP 游戏

这道题目让我更加理解BFS对于求最短路径的重要性,如果需要多次访问一个节点,可以在再添加一个维度。

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <queue>
#include <cstring>
#include <cstdio>

using namespace std;
const int MAXSIZE = 101;
int start[MAXSIZE][MAXSIZE];
int end[MAXSIZE][MAXSIZE];
bool visit[MAXSIZE][MAXSIZE][9999];

class Node {
public:
    int x, y, t;

    Node() {}

    Node(int x, int y, int t) : x(x), y(y), t(t) {}
};

int n, m;
int dir[4][2] = {{0,  1},
                 {1,  0},
                 {0,  -1},
                 {-1, 0}};

bool isin(int x, int y) {
    return x >= 1 && x <= n && y >= 1 && y <= m;
}

void bfs() {
    queue<Node> Q;
    while (!Q.empty()) Q.pop();
    visit[1][1][0] = true;
    Q.push(Node(1, 1, 0));
    while (!Q.empty()) {
        Node node = Q.front();
        Q.pop();
        if (node.x == n && node.y == m) {
            cout << node.t << endl;
            break;
        }
        for (int i = 0; i < 4; ++i) {
            Node next = node;
            next.x += dir[i][0];
            next.y += dir[i][1];
            next.t += 1;
            if (isin(next.x, next.y) && (next.t < start[next.x][next.y] || next.t > end[next.x][next.y]) &&
                !visit[next.x][next.y][next.t]) {
                Q.push(next);
                visit[next.x][next.y][next.t] = true;
            }
        }
    }
}

int main() {
//  freopen("../in.txt", "r", stdin);
    memset(start, -1, sizeof(start));
    memset(end, -1, sizeof(end));
    int x;
    cin >> n >> m >> x;
    int a, b, s, e;
    for (int i = 0; i < x; ++i) {
        cin >> a >> b >> s >> e;
        start[a][b] = s;
        end[a][b] = e;
    }
    bfs();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值