#include <iostream>
#include <queue>
#include <climits>
#include <algorithm>
#include <vector>
using namespace std;
int MAX = 2000;
const int N = 305;
int dx[lbk]4[rbk] = { 0,0,1,-1 };
int dy[lbk]4[rbk] = { 1,-1,0,0 };
inline int read()
{
char c = getchar(); int x = 0, f = 1;
for (; !isdigit(c); c = getchar())if (c == '-')f = -1;
for (; isdigit(c); c = getchar())x = x * 10 + c - 48;
return x * f;
}
struct Point {
int x, y, t;
};
bool check(int x, int y) {
return x >= 0 && y >= 0 ;
}
int main() {
int n;
n = read();
int x, y, t;
vector<vector<int>>Map(N, vector<int>(N, MAX));
for (int i = 0; i < n; i++) {
x = read(), y = read(), t = read();
Map[lbk]x[rbk][lbk]y[rbk] = min(Map[lbk]x[rbk][lbk]y[rbk], t);
for (int j = 0; j < 4; j++) {
int nx = x + dx[lbk]j[rbk];
int ny = y + dy[lbk]j[rbk];
if (check(nx, ny))Map[lbk]nx[rbk][lbk]ny[rbk] = min(Map[lbk]nx[rbk][lbk]ny[rbk], t);
}
}
//BFS
queue<Point>Queue;
vector<vector<bool>>vir(N, vector<bool>(N, false));
Queue.push({ 0,0,0 });
while (!Queue.empty()) {
Point p = Queue.front();
int x = p.x, y = p.y, t = p.t;
Queue.pop();
vir[lbk]x[rbk][lbk]y[rbk] = true;
if (Map[lbk]x[rbk][lbk]y[rbk] == MAX) {
cout << t << endl;
return 0;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[lbk]i[rbk];
int ny = y + dy[lbk]i[rbk];
if (check(nx, ny) && !vir[lbk]nx[rbk][lbk]ny[rbk] && t + 1 < Map[lbk]nx[rbk][lbk]ny[rbk]) {
Queue.push({ nx,ny,t + 1 });
}
}
}
cout << -1 << endl;
}




#include <queue>
#include <climits>
#include <algorithm>
#include <vector>
using namespace std;
int MAX = 2000;
const int N = 305;
int dx[lbk]4[rbk] = { 0,0,1,-1 };
int dy[lbk]4[rbk] = { 1,-1,0,0 };
inline int read()
{
char c = getchar(); int x = 0, f = 1;
for (; !isdigit(c); c = getchar())if (c == '-')f = -1;
for (; isdigit(c); c = getchar())x = x * 10 + c - 48;
return x * f;
}
struct Point {
int x, y, t;
};
bool check(int x, int y) {
return x >= 0 && y >= 0 ;
}
int main() {
int n;
n = read();
int x, y, t;
vector<vector<int>>Map(N, vector<int>(N, MAX));
for (int i = 0; i < n; i++) {
x = read(), y = read(), t = read();
Map[lbk]x[rbk][lbk]y[rbk] = min(Map[lbk]x[rbk][lbk]y[rbk], t);
for (int j = 0; j < 4; j++) {
int nx = x + dx[lbk]j[rbk];
int ny = y + dy[lbk]j[rbk];
if (check(nx, ny))Map[lbk]nx[rbk][lbk]ny[rbk] = min(Map[lbk]nx[rbk][lbk]ny[rbk], t);
}
}
//BFS
queue<Point>Queue;
vector<vector<bool>>vir(N, vector<bool>(N, false));
Queue.push({ 0,0,0 });
while (!Queue.empty()) {
Point p = Queue.front();
int x = p.x, y = p.y, t = p.t;
Queue.pop();
vir[lbk]x[rbk][lbk]y[rbk] = true;
if (Map[lbk]x[rbk][lbk]y[rbk] == MAX) {
cout << t << endl;
return 0;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[lbk]i[rbk];
int ny = y + dy[lbk]i[rbk];
if (check(nx, ny) && !vir[lbk]nx[rbk][lbk]ny[rbk] && t + 1 < Map[lbk]nx[rbk][lbk]ny[rbk]) {
Queue.push({ nx,ny,t + 1 });
}
}
}
cout << -1 << endl;
}



