1 #include<cstdio>
2 #include<cstdlib>
3 #include<cmath>
4 #include<cstring>
5 #include<algorithm>
6 #include<iostream>
7 #include<vector>
8 #include<map>
9 #include<set>
10 #include<queue>
11 #define inf 1000000000
12 #define maxn 300+10
13 #define maxm 500+100
14 #define ll long long
15 using namespace std;
16 inline ll read()
17 {
18 ll x=0,f=1;char ch=getchar();
19 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
20 while(ch>=‘0‘&&ch<=‘9‘){x=10*x+ch-‘0‘;ch=getchar();}
21 return x*f;
22 }
23 struct node
24 {
25 int x,y,time;
26 node(){}
27 node(int _x,int _y,int _time){x=_x;y=_y;time=_time;}
28 };
29 int dx[]={0,1,-1,0};
30 int dy[]={1,0,0,-1};
31 int v[maxn][maxn],vis[maxn][maxn];
32 queue<node>q;
33 void bfs()
34 {
35 node now=node(0,0,0);
36 vis[0][0]=1;
37 if(v[0][0]>0)q.push(now);
38 int ans=-1;
39 while(!q.empty())
40 {
41 now=q.front();q.pop();
42 if(v[now.x][now.y]==inf)
43 {
44 ans=now.time;
45 break;
46 }
47 for(int i=0;i<4;i++)
48 {
49 int xx=now.x+dx[i],yy=now.y+dy[i];
50 if(xx>=0&&yy>=0&&now.time+1<v[xx][yy]&&!vis[xx][yy])
51 {
52 vis[xx][yy]=1;
53 q.push(node(xx,yy,now.time+1));
54 }
55 }
56 }
57 printf("%d\n",ans);
58 }
59 int main()
60 {
61 freopen("input.txt","r",stdin);
62 freopen("output.txt","w",stdout);
63 int n=read();
64 for(int i=0;i<maxn;i++)
65 for(int j=0;j<maxn;j++)
66 v[i][j]=inf;
67 while(n--)
68 {
69 int x,y,t,xx,yy;
70 x=read();y=read();t=read();
71 v[x][y]=min(v[x][y],t);
72 for(int i=0;i<4;i++)
73 {
74 xx=x+dx[i];yy=y+dy[i];
75 if(xx>=0&&yy>=0)v[xx][yy]=min(v[xx][yy],t);
76 }
77 }
78 bfs();
79 return 0;
80 }