#include <bits/stdc++.h>
#include <utility>
#include <queue>
using namespace std;
int fx[5] = { 0,1,-1,0,0 };
int fy[5] = { 0,0, 0,1,-1 };
queue< pair<int, int> >q;
int a[350][350] = { 0 };
int ans[350][350] = { 0 };
int t[350][350];
int main()
{
int num;
cin >> num;
memset(t, -1, sizeof(t));
while (num--)
{
int x, y, ti;
cin >> x >> y >> ti;
if (ti < t[x][y] || t[x][y] == -1)
{
t[x][y] = ti;
}
for (int i = 0; i < 5; i++)
{
if ((x + fx[i]) >= 0 && (y + fy[i]) >= 0 && (ti <= t[x][y] || t[x][y] == -1))
t[x + fx[i]][y + fy[i]] = ti;
}
}
q.push(make_pair(0, 0));
a[0][0] = 1;
while (!q.empty())
{
for (int i = 0; i < 5; i++)
{
int tx = q.front().first + fx[i];
int ty = q.front().second + fy[i];
int now = ans[q.front().first][q.front().second] + 1;
if (tx >= 0 && ty >= 0 && a[tx][ty] == 0 && (now < t[tx][ty] || t[tx][ty] == -1))
{
a[tx][ty] = 1;
ans[tx][ty] = now;
q.push(make_pair(tx, ty));
if (t[tx][ty] == -1)
{
cout << ans[tx][ty];
return 0;
}
}
}
q.pop();
}
cout << -1;
return 0;
}