#include <bits/stdc++.h>
using namespace std;
const int maxn = 112345;
const int inf = 0x3f3f3f3f;
int n, m, p[maxn], q[maxn], c[maxn], d[maxn];
vector<long long> id;
vector<pair<int, int>> G[maxn];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>
    que;
inline int get(long long x) {
  return lower_bound(id.begin(), id.end(), x) - id.begin() + 1;
}
inline void addedge(int u, int v, int w) {
  G[u].push_back(pair<int, int>(v, w));
  G[v].push_back(pair<int, int>(u, w));
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; ++i) scanf("%d%d%d", &p[i], &q[i], &c[i]);
  for (int i = 1; i <= n; ++i) id.push_back(i);
  for (int i = 1; i <= m; ++i) {
    id.push_back(p[i] * 1000000ll + c[i]);
    id.push_back(q[i] * 1000000ll + c[i]);
  }
  sort(id.begin(), id.end());
  for (int i = 1; i <= m; ++i) {
    addedge(get(p[i]), get(p[i] * 1000000ll + c[i]), 1);
    addedge(get(q[i]), get(q[i] * 1000000ll + c[i]), 1);
    addedge(get(p[i] * 1000000ll + c[i]), get(q[i] * 1000000ll + c[i]), 0);
  }
  memset(d, 0x3f, sizeof d);
  d[get(1)] = 0;
  que.push(pair<int, int>(0, get(1)));
  while (!que.empty()) {
    int u = que.top().second;
    int o = que.top().first;
    que.pop();
    if (o > d[u]) continue;
    for (int i = 0; i < (int)G[u].size(); ++i) {
      int v = G[u][i].first;
      int w = G[u][i].second;
      if (d[v] > d[u] + w) {
        d[v] = d[u] + w;
        que.push(pair<int, int>(d[v], v));
      }
    }
  }
  if (d[n] == inf) d[n] = -2;
  printf("%d\n", d[n] / 2);
  return 0;
}
