#include <bits/stdc++.h>
 
using namespace std;
 
queue < int > que[200001];
unordered_map< int, bool > v[100000];
bool visited[100000];
int N, M;
unordered_map< int, vector< int > > g[100001];
vector< pair< int, int > > graph[100000];
 
void dfs(queue< int >& q, int idx, const int cc)
{
  if(v[idx][cc]++) return;
  if(!visited[idx]++) q.push(idx);
  for(auto to : g[idx][cc]) dfs(q, to, cc);
}
 
int main()
{
  cin >> N >> M;
  for(int i = 0; i < M; i++) {
    int p, q, c;
    cin >> p >> q >> c;
    --p, --q;
    g[p][c].push_back(q);
    g[q][c].push_back(p);
    graph[p].push_back({q, c});
    graph[q].push_back({p, c});
  }
 
  que[0].push(0);
  visited[0] = true;
  for(int i = 0; !que[i].empty(); i++) {
    while(!que[i].empty()) {
      int p = que[i].front();
      if(p == N - 1) {
        cout << i << endl;
        return (0);
      }
      for(auto to : graph[p]) dfs(que[i + 1], to.first, to.second);
      que[i].pop();
    }
  }
  cout << -1 << endl;
}