#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, m;
  cin >> n >> m;
  vector<vector<pair<int, int>>> g(n);
  while (m--) {
    int x, y, z;
    cin >> x >> y >> z;
    x--; y--;
    g[x].emplace_back(y, z);
    g[y].emplace_back(x, z);
  }
  vector<int> d(n, INT_MAX);
  vector<set<int>> s(n);
  priority_queue<pair<int, int>> pq;
  // priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
  pq.emplace(d[0] = 0, 0);
  while (!pq.empty()) {
    int expected, v;
    tie(expected, v) = pq.top();
    pq.pop();
    if (-expected != d[v]) {
      continue;
    }
    // if (expected != d[v]) {
    //   continue;
    // }
    for (const auto& e : g[v]) {
      int to, c;
      tie(to, c) = e;
      int dist = d[v] + !s[v].count(c);
      if (dist < d[to]) {
        s[to].clear();
        s[to].insert(c);
        pq.emplace(-(d[to] = dist), to);
        // pq.emplace(d[to] = dist, to);
      } else if (dist == d[to]) {
        s[to].insert(c);
      }
    }
  }
  cout << (d[n - 1] == INT_MAX ? -1 : d[n - 1]) << '\n';
  return 0;
}