#include<algorithm>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>

const int Maxv = 200005; 
int Head[Maxv], nHead[Maxv], vis[Maxv], book[Maxv], dist[Maxv], cnt, cnt1, n, m; 
std::vector< std::pair<int, int> > g[Maxv]; 
std::vector<int> ng[Maxv], cg[Maxv]; 

struct Node{
    int v, c, next; 
}e[Maxv], ne[Maxv]; 

inline int read(){
    int x = 0, f = 1; 
    char ch = getchar(); 
    while (ch < '0' || ch > '9') {
        if (ch == '-') {
            f = -1; 
        }
        ch = getchar(); 
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + ch - '0'; 
        ch = getchar(); 
    }
    return x * f; 
}

void bfs(){
    std::queue<int> q; 
    int wow = n; 
    for (int i = 0; i < Maxv; i++) {
        if (cg[i].empty()) {
            continue; 
        }
        for (int j = 0; j < cg[i].size(); j++) {
            int v = cg[i][j]; 
            if (vis[v] == i) {
                continue; 
            }
            q.push(v); 
            vis[v] = i; 
            while (!q.empty()) {
                int tmp = q.front(); 
                q.pop(); 
                while (book[tmp] < g[tmp].size()) {
                    int c = g[tmp][ book[tmp] ].first; 
                    if (c != i) {
                        break; 
                    }
                    int u = g[tmp][ book[tmp] ].second; 
                    if (vis[u] != i) {
                        vis[u] = i; 
                        q.push(u); 
                    }
                    book[tmp]++; 
                }
                ng[tmp].push_back(wow); 
                ng[wow].push_back(tmp); 
            }
            wow++; 
        }
    }
    for (int i = 0; i < Maxv; i++) {
        dist[i] = -2; 
    }
    q.push(0); 
    dist[0] = 0;
    while (!q.empty()) {
        int tmp = q.front(); 
        q.pop(); 
        for (int i = 0; i < ng[tmp].size(); i++) {
            int u = ng[tmp][i]; 
            if (dist[u] == -2) {
                dist[u] = dist[tmp] + 1; 
                q.push(u); 
            }
        }
    }
}

int main(){
    n = read(); 
    m = read(); 
    for (int i = 1; i <= m; i++) {
        int u, v, c; 
        u = read(); 
        v = read(); 
        c = read(); 
        g[u].push_back(std::make_pair(c, v)); 
        g[v].push_back(std::make_pair(c, u)); 
        cg[c].push_back(u);
        cg[c].push_back(v); 
    }
    for (int i = 0; i < n; i++) {
        std::sort(g[i].begin(), g[i].end()); 
        vis[i] = -1; 
    }
    bfs(); 
    printf("%d\n", dist[n - 1] / 2); 
    return 0; 
}