var
way:array[1..4,1..2] of longint=((1,0),(0,1),(-1,0),(0,-1));
a,zx:array[0..101,0..101] of longint;
m,n,i,j,x,y,k,ans:longint;
proceduredg(x,y,s:longint);var
i,j,xx,yy,x2,y2:longint;
beginif s>=zx[x,y] thenexitelse zx[x,y]:=s;
if (x=m) and (y=m) thenbeginif ans>s then ans:=s;
exit;
end;
for i:=1to4dobegin
xx:=x+way[i,1];
yy:=y+way[i,2];
if (xx>=1) and (yy>=1) and (xx<=m) and (yy<=m) thenbeginif a[xx,yy]=maxlongint thenbeginif (xx=m) and (yy=m) then dg(xx,yy,s+2);
for j:=1to4dobegin
x2:=xx+way[j,1];
y2:=yy+way[j,2];
if (x2>=1) and (y2>=1) and (x2<=m) and (y2<=m) thenbeginif a[x2,y2]<>maxlongint thenbeginif a[x2,y2]<>a[x,y] then dg(x2,y2,s+3)
else dg(x2,y2,s+2);
end;
end;
end;
endelseif a[x,y]<>a[xx,yy] then dg(xx,yy,s+1)
else dg(xx,yy,s);
end;
end;
end;
begin
assign(input,'chess.in');reset(input);
assign(output,'chess.out');rewrite(output);
for i:=0to101dofor j:=0to101dobegin
a[i,j]:=maxlongint;
zx[i,j]:=maxlongint;
end;
readln(m,n);
for i:=1to n dobeginread(x,y,k);
a[x,y]:=k;
end;
ans:=maxlongint;
dg(1,1,0);
if ans=maxlongint then writeln(-1)
else writeln(ans);
close(input);
close(output);
end.