#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

int d[100000];
set <int> s[100000];
map <int, vector<int> > mp[100000];

void dfs(int x, int y, int z, queue <int> &q) {
    int i;
    
    s[x].insert(y);
    
    if (d[x] > z) {
        d[x] = z;
        q.push(x);
    }
    
    for (i = 0; i < mp[x][y].size(); i++) {
        int nx = mp[x][y][i];
        
        if (!s[nx].count(y)) dfs(nx, y, z, q);
    }
}

int main() {
    int n, m, i;
    queue <int> q;
    
    scanf("%d %d", &n, &m);
    
    for (i = 0; i < m; i++) {
        int x, y, z;
        
        scanf("%d %d %d", &x, &y, &z);
        
        x--;
        y--;
        
        mp[x][z].push_back(y);
        mp[y][z].push_back(x);
    }
    
    for (i = 0; i < n; i++) d[i] = 1e9;
    
    d[0] = 0;
    q.push(0);
    
    while (!q.empty()) {
        int x = q.front();
        map <int, vector <int> >::iterator it;
        
        q.pop();
        
        if (x == n - 1) {
            printf("%d\n", d[n - 1]);
            
            return 0;
        }
        
        for (it = mp[x].begin(); it != mp[x].end(); it++) {
            if (!s[x].count(it->first)) dfs(x, it->first, d[x] + 1, q);
        }
    }
    
    puts("-1");
    
    return 0;
}
