#include <bits/stdc++.h>
using namespace std;
struct node
{
int x,y,s,coin;
}t,u;
queue <node> q;
int n,m;
int cost[105][105];
int mapp[105][105];
int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
void bfs()
{
q.push({1,1,mapp[1][1],0});
while(!q.empty())
{
t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int nx=t.x+d[i][0];
int ny=t.y+d[i][1];
int c1=mapp[t.x][t.y],c2=mapp[nx][ny],v=t.coin;
if(c1!=-1 && c2!=-1)
{
if(c1!=c2) v++;
if(v<cost[nx][ny])
{
cost[nx][ny]=v;
q.push({nx,ny,c2,v});
}
}
else if(c1!=-1 && c2==-1)
{
v+=2;
if(v<cost[nx][ny])
{
cost[nx][ny]=v;
q.push({nx,ny,c1,v});
}
}
else if(c1==-1 && c2!=-1)
{
if(c1!=c2) v++;
if(v<cost[nx][ny])
{
cost[nx][ny]=v;
q.push({nx,ny,c2,v});
}
}
}
}
}
int main()
{
memset(mapp,-1,sizeof(mapp));
memset(cost,0x3f,sizeof(cost));
cost[1][1]=0;
cin >> m >> n;
while(n--)
{
int xx,yy,a;
cin >> xx >> yy >> a;
mapp[xx][yy]=a;
}
bfs();
if(cost[m][m]==0x3f3f3f3f)
{
cout << -1;
return 0;
}
cout << cost[m][m];
return 0;
}