1 #include<cstdio>
2 #include<iostream>
3 #include<queue>
4 using namespace std;
5
6 const int dir[4][2] = {{0,1},{1,0},{-1,0},{0,-1}},inf = 0x3f3f3f3f;
7 int map[400][400],n;
8
9 struct node{
10 int x,y,time;
11 };
12
13 bool Judge(int x,int y){
14 return x < 0 || y < 0;
15 }
16
17 void Init(){
18 for(int i = 0;i <= 355;i++){
19 for(int j = 0;j <= 355;j++){
20 map[i][j] = inf;
21 }
22 }
23 }
24
25 void Print(){
26 for(int i = 0;i <= 7;i++){
27 for(int j = 0;j <= 7;j++){
28 if(map[i][j] != inf) printf("%d ",map[i][j]);
29 else cout << 0 << ‘ ‘;
30 }cout << endl;
31 }
32 cout << endl;
33 }
34
35 void bfs(){
36 queue<node> Q;
37 Q.push((node){0,0,0});
38 // book[0][0] = true;
39
40 while(!Q.empty()){
41 node now = Q.front();
42 Q.pop();
43
44 for(int i = 0;i < 4;i++){
45 int nowx = now.x+dir[i][0];
46 int nowy = now.y+dir[i][1];
47
48 if(Judge(nowx,nowy) || map[nowx][nowy] <= now.time+1) continue;
49
50 if(map[nowx][nowy] == inf){
51 printf("%d",now.time+1);
52 return;
53 }
54
55 map[nowx][nowy] = now.time+1;
56 Q.push((node){nowx,nowy,now.time+1});
57
58 // Print();
59 }
60 }
61
62 printf("-1");
63 }
64
65 int main(){
66 scanf("%d",&n);
67 Init();
68 for(int i = 1;i <= n;i++){
69 int a,b,t;
70 scanf("%d%d%d",&a,&b,&t);
71 map[a][b] = min(map[a][b],t);
72 for(int i = 0;i < 4;i++){
73 int nowx = a+dir[i][0];
74 int nowy = b+dir[i][1];
75 if(Judge(nowx,nowy)) continue;
76 map[nowx][nowy] = min(map[nowx][nowy],t);
77 }
78 }
79
80 if(map[0][0] == inf) printf("0");
81 else if(map[0][0] == 0) printf("-1");
82 else bfs();
83
84 return 0;
85 }