#include<bits/stdc++.h>
#define INF 0x7fffffff
#define ll long long
#define P pair<int,int>
#define MP(a,b) make_pair(a,b)
using namespace std;
bool vis[200005];
int n,m,dis[200005],head,tail,t,h[200005];
priority_queue<P> q;
set<int> in[200005];
struct E{int v,c,next;}g[400005];
void ins(int u,int v,int c){g[++t].v=v,g[t].c=c,g[t].next=h[u],h[u]=t;}
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
    return x*f;
}
int main(){
	memset(dis,0x3f,sizeof dis);
	n=read(),m=read();
	for(int i=1;i<=m;++i){
		int u,v,c;
		u=read(),v=read(),c=read();
		ins(u,v,c); ins(v,u,c);
	}
	q.push(MP(0,1)); dis[1]=0;
	while(!q.empty()){
		int u=q.top().second,cost=-q.top().first;
		q.pop();
		vis[u]=1;
		if(cost>dis[u]) continue;
		for(int j=h[u];j;j=g[j].next){
			if(vis[g[j].v]) continue;
			int v=g[j].v,c=g[j].c,d=dis[u]+(!in[u].count(c));
			if(d>dis[v]) continue;
			if(d<dis[v]){
				q.push(MP(-d,v));
				dis[v]=d;
				in[v].clear();
			}
			in[v].insert(c);
		}
	}
	printf("%d",dis[n]==1061109567?-1:dis[n]);
}