#include <bits/stdc++.h>
using namespace std;
const int N=300,SAFE=30001;
int m,T[N+5][N+5];
bool vis[N+5][N+5];
int dir[5][2]={0,0,1,0,-1,0,0,0,1,-1};
struct node{
int x,y,ans;
};
inline bool check(int x,int y){
if (x< 0||y<0)
return false;
return true;
}
queue<node>q;
int main(){
cin >>m;
for(int i=1;i<=N+5;i++){
for(int j=1;j<=N+5;j++){
T[i][j]=SAFE;
}
}
for(int k=1;k<=m;k++){
int x,y,t;
cin >>x>>y>>t;
for(int i=0;i<=4;i++){
int nx=x+dir[i][0];
int ny=y+dir[i][1];
if(check(nx,ny) && t<T[nx][ny]){
T[nx][ny]=t;
}
}
}
vis[0][0]=true;
q.push({0,0,0});
while(!q.empty()){
node s=q.front();
q.pop();
if(T[s.x][s.y]==SAFE){
cout <<s.ans;
return 0;
}
for(int i=1;i<=4;i++){
int nx=s.x+dir[i][0];
int ny=s.y+dir[i][1];
if(check(nx,ny) && !vis[nx][ny] && T[nx][ny]>s.ans+1){
q.push({nx,ny,s.ans+1});
vis[nx][ny]=true;
}
}
}
cout <<-1;
return 0;
} ```