1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <bits/stdc++.h>
using namespace std;
const int LEN = 350;
int ans = -1, vis[LEN][LEN], table[LEN][LEN], walk[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
struct Node { int x_, y_, t_; Node(int x, int y, int t) : x_(x), y_(y), t_(t) {} };
queue<Node> q;
void init() { memset(table, -1, sizeof(table)); int n, x, y, t; cin >> n; while (n--) { cin >> x >> y >> t; if (table[x][y] == -1) table[x][y] = t; else table[x][y] = min(t, table[x][y]); for (int i = 0; i < 4; ++i) { int nxt_x = x + walk[i][0], nxt_y = y + walk[i][1]; if (nxt_x < 0 || nxt_y < 0) continue; table[nxt_x][nxt_y] = table[nxt_x][nxt_y] == -1 ? t : min(table[nxt_x][nxt_y], t); } } q.emplace(0, 0, 0); vis[0][0] = 1; }
void bfs() { while (!q.empty()) { Node u = q.front(); q.pop(); int ux = u.x_, uy = u.y_, ut = u.t_; if (table[ux][uy] == -1) { ans = ut; return; } for (int i = 0; i < 4; ++i) { int x = ux + walk[i][0], y = uy + walk[i][1], t = ut + 1; if (x < 0 || y < 0 || vis[x][y] || (table[x][y] != -1 && table[x][y] <= t)) continue; q.emplace(x, y, t); vis[x][y] = 1; } } }
int main() { init(); bfs(); cout << ans << endl; return 0; }
|