#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=22e5+10;
int N,M;
int dist[maxn],vis[maxn];
struct Rail{int y,val;};
struct node
{
    int y,c;
    friend bool operator<(node A,node B){return (A.y==B.y)?(A.c<B.c):(A.y<B.y);}
};
struct Node{int y,Next,c;};
vector<node> real_emp;
vector<Node> emp_emp;
vector<Rail> v[maxn];
inline long long read()
{
    long long s=0,f=1; char ch; for(;ch<'0'||ch>'9';ch=getchar()) if(ch=='-') f=-1;
    for(;ch>='0'&&ch<='9';ch=getchar()) s=(s<<3)+(s<<1)+ch-'0'; return s*f;
}
void Dj(int st)
{
    priority_queue< pair<int,int> > q;
    memset(dist,0x3f,sizeof(dist));
    memset(vis,0,sizeof(vis));
    dist[st]=0; q.push(make_pair(0,st));
    while(!q.empty())
    {
        int x=q.top().second; q.pop();
        if(vis[x]) continue; vis[x]=1;
        for(register int i=0;i<v[x].size();++i)
        {
            int y=v[x][i].y,val=v[x][i].val;
            if(dist[y]>dist[x]+val)
            {
                dist[y]=dist[x]+val;
                q.push(make_pair(-dist[y],y));
            }
        }
    }
}
void Input()
{
    N=read(),M=read();
    int xx,yy,zz;
    for(register int i=1;i<=M;++i)
    {
        xx=read()-1,yy=read()-1,zz=read()-1;
        real_emp.push_back((node){xx,zz});
        real_emp.push_back((node){yy,zz});
        emp_emp.push_back((Node){xx,yy,zz});
        emp_emp.push_back((Node){yy,xx,zz});
    }
}
void Solution()
{
    Input();
    sort(real_emp.begin(),real_emp.end());
    for(register int i=0;i<real_emp.size();++i)
    {
        v[N+i].push_back((Rail){real_emp[i].y,1});
        v[real_emp[i].y].push_back((Rail){N+i,1});
    }
    for(register int i=0;i<emp_emp.size();++i)
    {
        int pos1=lower_bound(real_emp.begin(),real_emp.end(),(node){emp_emp[i].y,emp_emp[i].c})-real_emp.begin();
        int pos2=lower_bound(real_emp.begin(),real_emp.end(),(node){emp_emp[i].Next,emp_emp[i].c})-real_emp.begin();
        v[N+pos1].push_back((Rail){N+pos2,0});
    }
    Dj(0);
    printf("%d\n",(dist[N-1]==1061109567)?-1:(dist[N-1]>>1)); exit(0);
}
int main()
{
    Solution();
}
