#include<bits/stdc++.h>
using namespace std;
const int N=600005;
map<pair<int,int>,int>mp;
vector<pair<int,int>>e[N];
int n,m,cnt,vis[N];
priority_queue<pair<int,int>>q;
void add(int p,int q,int c,int d)
{
	e[p].push_back({q,c});
	e[q].push_back({p,d});
}
int solve(int u,int v)
{
	if(mp.count({u,v}))
		return mp[{u,v}];
	int ret=cnt++;
	add(u,ret,1,0);
	return mp[{u,v}]=ret;
}
int main()
{
	scanf("%d%d",&n,&m);
	cnt=n+1;
	for(int i=1;i<=m;i++)
	{
		int p,q,c;
		scanf("%d%d%d",&p,&q,&c);
		int a=solve(p,c),b=solve(q,c);
		add(a,b,0,0);
	}
	q.push({0,1});
	while(!q.empty())
	{
		pair<int,int> tmp=q.top();
		q.pop();
		int cost=-tmp.first,pt=tmp.second;
		if(vis[pt])
			continue;
		vis[pt]=1;
		if(pt==n)
		{
			printf("%d\n",cost);
			return 0;
		}
		for(auto it:e[pt])
			q.push({-(cost+it.second),it.first});
	}
	puts("-1");
	return 0;
}