def bfs():
dic=[[-1,0],[1,0],[0,-1],[0,1]]
for i in range(M):
if time[g[i][0]][g[i][1]]==-1 or time[g[i][0]][g[i][1]]>g[i][2]:
time[g[i][0]][g[i][1]] = g[i][2]
for j in range(4):
x,y=g[i][0]+dic[j][0],g[i][1]+dic[j][1]
if 0<=x<301 and 0<=y<301:
if time[x][y]==-1 or g[i][2]<time[x][y]:
time[x][y]=g[i][2]
q=[]
q.append([0,0,0])
visit[0][0]=True
while len(q)!=0:
p=q.pop(0)
if time[p[0]][p[1]]==-1:
return time[p[0]][p[1]]
for i in range(4):
x, y = p[0] + dic[i][0], p[1] + dic[i][1]
if 0 <= x < 301 and 0 <= y < 301:
if time[x][y] == -1:
return p[2] + 1
if 0<=x<301 and 0<=y<=300 and visit[x][y]==False:
if (time[x][y]==-1 or time[x][y]-1>p[2]):
q.append([x,y,p[2]+1])
visit[x][y]=True
return -1
M=int(input())
g=[list(map(int,input().split())) for i in range(M)]
time=[[-1]*301 for i in range(301)]
visit=[[False]*301 for i in range(301)]
print(bfs())