
#include <bits/stdc++.h>
using namespace std;
#define rep(i,m,n) for(int i=m;i<=n;i++)
const int M = 1e5 + 10;
const int inf = 0x3f3f3f3f;

//*************************************
int n,m,cnt;
int head[M];
struct node {
	int to,id,nxt;
} E[M << 2];
void add(int u,int v,int id) {
	E[++cnt] = {v,id,head[u]};
	head[u] = cnt;
}
//*************************************
int dis[M],ind[M];
set<int> vis[M];
void a() {
	priority_queue<pair<int, int> > Q;
	Q.push({0,1});
	dis[1] = 0;
	while(!Q.empty()) {
		int now =  Q.top().second;
		int   d = -Q.top().first;
			  	   Q.pop();
		if(dis[now] < d) continue;
		for(int i=head[now]; i; i=E[i].nxt) {
			int    v = E[i].to;
			int   id = E[i].id;
			int cost = d + (!vis[now].count(id));
			if(dis[v] > cost) {
				dis[v] = cost;
				Q.push({-cost,v});
				vis[v].clear();
				vis[v].insert(id);
			} else if(dis[v] == cost) {
				if(ind[v] <= 2) 
					ind[v]++,
					Q.push({-cost,v});
				vis[v].insert(id);
			}
		}
	}
	printf("%d\n",dis[n] == inf? -1:dis[n]);
}
//******************************************
void init() {
	rep(i,1,n) {
		head[i] = 0;
		dis[i] = inf;
		ind[i] = 0;
		vis[i].clear();
	}
	cnt = 0;
}
int main() {
	while(~scanf("%d %d",&n,&m)) {
		init();
		while(m--) {
			int a,b,c;
			scanf("%d %d %d",&a,&b,&c);
			add(a,b,c);
			add(b,a,c);
		}
		a();
	}
}