#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100005;
struct edge {
  int to, kind;
};
vector<edge> G[MAX_N];
map<int, int> d[MAX_N];
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < (int)(m); ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    --a, --b, --c;
    G[a].push_back((edge){b, c}), G[b].push_back((edge){a, c});
  }
  deque<pair<int, int> > que;
  que.push_back(pair<int, int>(0, -1));
  d[0][-1] = 0;
  while (!que.empty()) {
    pair<int, int> p = que.front();
    que.pop_front();
    int dist = d[p.first][p.second];
    for (auto&(e) : (G[p.first])) {
      auto it = d[e.to].find(e.kind);
      if (it == d[e.to].end() || it->second > dist + (e.kind != p.second)) {
        d[e.to][e.kind] = dist + (e.kind != p.second);
        if ((e.kind != p.second)) {
          que.push_back(pair<int, int>(e.to, e.kind));
        } else {
          que.push_front(pair<int, int>(e.to, e.kind));
        }
      }
    }
  }
  int mn = 1000000005;
  for (auto&(it) : (d[n - 1])) {
    mn = min(mn, it.second);
  }
  if (mn < 1000000005) {
    cout << mn << "\n";
  } else {
    cout << "-1\n";
  }
  return 0;
}
