#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<set>
#define MN 400005
#define inf 0x3f3f3f3f
using namespace std;
int n,m,num,head[MN],dis[MN];
struct edge{int to,next,w;}g[MN<<1];
void ins(int u,int v,int w){g[++num].next=head[u];head[u]=num;g[num].to=v;g[num].w=w;}
struct node{
	int x,val;
	friend bool operator<(node x,node y){return x.val>y.val;}
};
set<int> now[MN];
priority_queue<node> q;
int main(){
	scanf("%d%d",&n,&m);memset(dis,0x3f,sizeof(dis));int x,y,v;
	for(int i=1;i<=m;i++)scanf("%d%d%d",&x,&y,&v),ins(x,y,v),ins(y,x,v);q.push((node){1,dis[1]=0});
	while(!q.empty()){
		node tmp=q.top();q.pop();if(dis[tmp.x]<tmp.val)continue;
		for(int i=head[tmp.x];i;i=g[i].next){
			int d=tmp.val+(!now[tmp.x].count(g[i].w));
			if(dis[g[i].to]>d){
				q.push((node){g[i].to,dis[g[i].to]=d});
				now[g[i].to].clear();now[g[i].to].insert(g[i].w);
			}else if(dis[g[i].to]==d)now[g[i].to].insert(g[i].w),q.push((node){g[i].to,d});
		}
	}printf("%d\n",dis[n]==inf?-1:dis[n]);
}