#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
queue<pair<PII,int>> q;
map<PII, int> um;
map<PII, int> cost;
int xm[4] = { 1,0,-1,0 };
int ym[4] = { 0,1,0,-1 };
int m, n, x, y, c;
int bfs(int x, int y)
{
q.push({ { x,y }, um[{x, y}] });
cost[{x, y}] = 1;
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int a = t.first.first + xm[i]; int b = t.first.second + ym[i];
if (a < 1 || a > m || b < 1 || b > m ||(cost[{a, b}] && cost[{t.first.first,t.first.second}] >= cost[{a,b}])) continue;
int cs = um[{a, b}]; int cf = t.second;
if(!cost[{a, b}]) cost[{a, b}] = 0x3f3f3f3f;
if (cs && cs == cf)
{
cost[{a, b}] = min(cost[{a, b}],cost[{t.first.first, t.first.second}]);
q.push({ { a,b }, cs});
}
else if (cs && cf && cs != cf)
{
cost[{a, b}] = min(cost[{a, b}] , cost[{t.first.first, t.first.second}] + 1);
q.push({ { a,b }, cs});
}
else if (cf && !cs)
{
if (um[{t.first.first, t.first.second}] == 0) continue;
cost[{a, b}] = min(cost[{a, b}],cost[{t.first.first, t.first.second}] + 2);
q.push({ { a,b }, 1});
q.push({ { a,b }, 2});
}
}
}
return cost[{m,m}] == 0 ? -1 : cost[{m,m}];
}
int main()
{
cin >> m >> n;
for (int i = 1; i <= n; i++)
{
cin >> x >> y >> c;
um[{x, y}] = c + 1;
}
cout << bfs(1, 1);
return 0;
}