#include <queue>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define x first
#define y second
#define pb push_back
typedef pair<int, int> pii;
const int maxn = 1000005;
vector<pii> ver, line[maxn];
vector<int> g[maxn];
int n, m, fa[maxn], cur, was[maxn], newn, dis[maxn];
int getfa(int u) {
    return fa[u] == u ? u : fa[u] = getfa(fa[u]);
}
void merge(int u, int v) {
    if (was[u] != cur) {
        was[u] = cur;
        ver.pb(pii(0, u));
        fa[u] = u;
    }
    if (was[v] != cur) {
        was[v] = cur;
        ver.pb(pii(0, v));
        fa[v] = v;
    }
    fa[getfa(u)] = getfa(v);
}
int main() {
	freopen("trip.in","r",stdin);
	freopen("trip.out","w",stdout);
    scanf("%d %d", &n, &m), newn = n;
    for (int u, v, w, i = 1; i <= m; i++) {
        scanf("%d %d %d", &u, &v, &w);
        line[w].pb(pii(u, v));
    }
    for (int i = 1; i <= 1000000; i++) {
        ver.clear(), ++cur;
        for (int j = 0; j < line[i].size(); j++) {
            merge(line[i][j].x, line[i][j].y);
        }
        for (int j = 0; j < ver.size(); j++) {
            ver[j].x = getfa(ver[j].y);
        }
        sort(ver.begin(), ver.end());
        for (int j = 0, k = 0; j < ver.size(); j = k) {
            ++newn;
            while (k < ver.size() && ver[j].x == ver[k].x) {
                g[newn].pb(ver[k].y);
                g[ver[k++].y].pb(newn);
            }
        }
    }
    queue<int> que;
    que.push(1);
    for (int i = 2; i <= newn; i++) {
        dis[i] = -2;
    }
    dis[1] = 0;
    while (!que.empty()) {
        int u = que.front();
        que.pop();
        for (int i = 0; i < g[u].size(); i++) {
            int v = g[u][i];
            if (dis[v] == -2) {
                dis[v] = dis[u] + 1;
                que.push(v);
            }
        }
    }
    printf("%d\n", dis[n] >> 1);
    return 0;
}
