#include<bits/stdc++.h>
using namespace std;
bool vis[305][305];
int m;
int fuzhu[305][305]={0};
typedef struct sss{
int x,y,t;
}sss;
int d[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
sss star[50005];
typedef struct ren{
int rx,ry;
}ren;
ren b;
bool compare(sss s1,sss s2){
return s1.t<s2.t;
}
void bfs(int sx, int sy, int tt) {
queue<ren> q;
q.push({sx, sy});
vis[sx][sy] = true;
int step = 1;
while (!q.empty()) {
int size = q.size();
while (step <= m && star[step].t == tt) {
for (int k = 0; k < 4; ++k) {
int nx = star[step].x + d[k][0];
int ny = star[step].y + d[k][1];
if (nx >= 0 && nx <= 300 && ny >= 0 && ny <= 300) {
vis[nx][ny]=true;
}
}
vis[star[step].x][star[step].y]=true;
step++;
}
for (int i = 0; i < size; ++i) {
ren c = q.front(); q.pop();
if (fuzhu[c.rx][c.ry] == 0) {
cout << tt << endl;
return;
}
for (int j = 0; j < 4; ++j) {
int dx = c.rx + d[j][0];
int dy = c.ry + d[j][1];
if (dx >= 0 && dx <= 300 && dy >= 0 && dy <= 300 && !vis[dx][dy]) {
q.push({dx, dy});
vis[dx][dy] = true;
}
}
}
tt++;
}
cout << "-1" << endl;
}
int main(){
cin>>m;
for(int i=1;i<=m;++i){
cin>>star[i].x>>star[i].y>>star[i].t;
fuzhu[star[i].x][star[i].y]=1;
fuzhu[star[i].x-1][star[i].y]=1;
fuzhu[star[i].x+1][star[i].y]=1;
fuzhu[star[i].x][star[i].y-1]=1;
fuzhu[star[i].x][star[i].y+1]=1;
}
sort(star+1,star+1+m,compare);
bfs(0,0,0);
return 0;
}