1. 程式人生 > >CCF CSP 遊戲

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(); }