#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int INF=0x3f3f3f3f;
typedef pair<int,int> pii;
map<pii,int> mp;
int n,m,x,y,u,v,cost,dis[810000];
int edgenum,vet[810000],val[810000],Next[810000],Head[810000];
bool vis[810000];
void addedge(int u,int v,int cost){
    vet[++edgenum]=v; val[edgenum]=cost;
    Next[edgenum]=Head[u]; Head[u]=edgenum;
}
struct node{
    int dis,num;
    bool operator<(const node &x) const{
        return dis<x.dis;
    }
} Heap[1610000];
void update(int i){
    while (i!=1){
        Heap[i>>1]=min(Heap[i],Heap[i^1]);
        i>>=1;
    }
    return;
}
void dijkstra(int n,int s){
    for (int i=1;i<(n<<1);i++){
        dis[i]=Heap[i].dis=INF;
        Heap[i].num=i;
    }
    dis[s]=0; Heap[s+(n-1)].dis=0; update(s+(n-1));
    while (Heap[1].dis!=INF){
        int num=Heap[1].num,u=num-(n-1);
        Heap[num].dis=INF;
        update(num);
        for (int e=Head[u];e;e=Next[e]){
            int v=vet[e];
            if (dis[v]>dis[u]+val[e]){
                dis[v]=dis[u]+val[e];
                Heap[v+(n-1)].dis=dis[u]+val[e];
                update(v+(n-1));
            }
        }
    }
}
int cnt;
int hs(int u,int c){
    pii t; t.first=u; t.second=c;
    if (!mp[t]) mp[t]=++cnt;
    return mp[t];
}

int main() {
    scanf("%d%d",&n,&m);
    cnt=n;
    for (int i=1;i<=m;i++){
        scanf("%d%d%d",&u,&v,&cost);
        x=hs(u,cost); y=hs(v,cost);
        addedge(x,y,0); addedge(y,x,0);
        addedge(u,x,1); addedge(x,u,1);
        addedge(v,y,1); addedge(y,v,1);
    }
    dijkstra(cnt,1);
    if (dis[n]<INF) printf("%d\n",dis[n]>>1);
    else puts("-1");
    return 0;
}
