1 #include <bits/stdc++.h>
2 using namespace std;
3
4 const int maxn=300+5,maxt=1000+5;
5 int n;
6 bool mark1[maxn][maxn];
7 bool mark2[maxn][maxn];
8 bool vis[maxn][maxn];
9 struct node{ int x,y; node(int x=0,int y=0):x(x),y(y){}};
10 struct nd{ int x,y,step; nd(int x=0,int y=0,int step=0):x(x),y(y),step(step){} };
11 vector <node> t[maxt];
12 int go[4][2]={ 0,-1,0,1,-1,0,1,0 };
13 void bfs(){
14 queue <nd> q;
15 q.push(nd(1,1,0));
16 int now=-1;
17 while(!q.empty()){
18 nd u=q.front(); q.pop();
19 if(!mark1[u.x][u.y]){
20 printf("%d\n",u.step);
21 return;
22 }
23 if(u.step!=now){
24 for(int i=0;i<t[u.step].size();i++){
25 int x=t[u.step][i].x,y=t[u.step][i].y;
26 mark2[x][y]=mark2[x-1][y]=mark2[x+1][y]=mark2[x][y-1]=mark2[x][y+1]=true;
27 }
28 now=u.step;
29 }
30 if(mark2[u.x][u.y]) continue;
31 for(int i=0;i<4;i++){
32 int tx=u.x+go[i][0],ty=u.y+go[i][1];
33 if(!vis[tx][ty]&&!mark2[tx][ty]&&tx>=1&&tx<=302&&ty>=1&&ty<=302){
34 vis[tx][ty]=true;
35 q.push(nd(tx,ty,u.step+1));
36 }
37 }
38 }
39 printf("-1\n");
40 }
41 void init(){
42 scanf("%d",&n);
43 for(int i=1;i<=n;i++){
44 int a,b,c;
45 scanf("%d%d%d",&a,&b,&c); a++; b++;
46 t[c].push_back(node(a,b));
47 mark1[a][b]=mark1[a-1][b]=mark1[a+1][b]=mark1[a][b-1]=mark1[a][b+1]=true;
48 }
49 }
50 int main(){
51 init();
52 bfs();
53 return 0;
54 }