1 /**************************************************************
2 Problem: 1611
3 User: HansBug
4 Language: Pascal
5 Result: Accepted
6 Time:140 ms
7 Memory:2976 kb
8 ****************************************************************/
9
10
11 const di:array[1..4,1..2] of longint=((1,0),(-1,0),(0,1),(0,-1));
12 var
13 i,j,k,l,m,n,x,y,a1,a2,a3,a4,f,r:longint;
14 a,b:array[-1..500,-1..500] of longint;
15 d:array[0..100000,1..2] of longint;
16 begin
17 fillchar(a,sizeof(a),0);
18 fillchar(b,sizeof(b),0);
19 readln(m);
20 for i:=1 to m do
21 begin
22 readln(j,k,l);inc(l);
23 if (b[j-1,k]=0) or (b[j-1,k]>l) then b[j-1,k]:=l;
24 if (b[j+1,k]=0) or (b[j+1,k]>l) then b[j+1,k]:=l;
25 if (b[j,k-1]=0) or (b[j,k-1]>l) then b[j,k-1]:=l;
26 if (b[j,k+1]=0) or (b[j,k+1]>l) then b[j,k+1]:=l;
27 if (b[j,k]=0) or (b[j,k]>l) then b[j,k]:=l;
28 end;
29 f:=1;r:=2;d[1,1]:=0;d[1,2]:=0;a[0,0]:=1;
30 if b[0,0]<=1 then
31 begin
32 writeln(-1);
33 halt;
34 end;
35 while f<r do
36 begin
37 for i:=1 to 4 do
38 begin
39 x:=d[f,1]+di[i,1];
40 y:=d[f,2]+di[i,2];
41 if (x<0) or (y<0) then continue;
42 if (a[x,y]=0) and (((a[d[f,1],d[f,2]]+1)<b[x,y]) or (b[x,y]=0)) then
43 begin
44 a[x,y]:=a[d[f,1],d[f,2]]+1;
45 if b[x,y]=0 then
46 begin
47 writeln(a[x,y]-1);
48 halt;
49 end;
50 d[r,1]:=x;d[r,2]:=y;
51 inc(r);
52 end;
53 end;
54 inc(f);
55 end;
56 writeln(-1);
57 end.