#include <stdio.h>
#include <string.h>
#include <map>
#include <queue>
#define MN 100000
#define MM 200000
int n,m,vn;
int hd[MN*5+5],to[MM*6+5],nxt[MM*6+5],val[MM*6+5];
int dis[MN*5+5];
bool vis[MN*5+5];
void add(int u,int v,int w){
	static int rn=0;
	to[rn]=v,nxt[rn]=hd[u],val[rn]=w;
	hd[u]=rn++;
}
int gid(int u,int c){
	static std::map<int,int> tb[MN+5];
	if(tb[u].find(c)==tb[u].end()){
		tb[u][c]=(++vn);
		add(u,tb[u][c],1);
		add(tb[u][c],u,0);
	}
	return tb[u][c];
}
void bfs01(){
	static std::deque<int> q;
	memset(dis,0x3f,sizeof(dis));
	dis[1]=0; q.push_front(1);
	while(!q.empty()){
		int u=q.front(); q.pop_front();
		if(vis[u]) continue; vis[u]=true;
		for(int i=hd[u];~i;i=nxt[i]){
			if(vis[to[i]]) continue;
			if(dis[u]+val[i]<dis[to[i]]){
				dis[to[i]]=dis[u]+val[i];
				if(val[i]==0)
					q.push_front(to[i]);
				else
					q.push_back(to[i]);
			}
		}
	}
}
int main(){
	memset(hd,0xff,sizeof(hd));
	scanf("%d%d",&n,&m);
	vn=n;
	for(int i=1,u,v,c;i<=m;i++){
		scanf("%d%d%d",&u,&v,&c);
		u=gid(u,c),v=gid(v,c);
		add(u,v,0),add(v,u,0);
	}
	bfs01();
	if(dis[n]==0x3f3f3f3f) puts("-1");
	else printf("%d\n",dis[n]);
}