import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;

alias Node = Tuple!(int, "v", int, "c", int, "cost");

enum inf = 1<<30;
int n, m;
int[int][] dist;
Node[][int][] adj;

void main() {
    scan(n, m);
    dist = new int[int][](n);
    foreach (i ; 0 .. n) {
        dist[i][0] = inf;
    }
    adj = new Node[][int][](n);
    foreach (i ; 0 .. m) {
        int pi, qi, ci;
        scan(pi, qi, ci);
        pi--, qi--;
        dist[pi][ci] = inf;
        dist[qi][ci] = inf;
        adj[pi][ci] ~= Node(qi, ci, 0);
        adj[qi][ci] ~= Node(pi, ci, 0);
    }
    foreach (i ; 0 .. n) {
        foreach (c ; adj[i].keys) {
            if (c == 0) continue;
            adj[i][0] ~= Node(i, c, 1);
            adj[i][c] ~= Node(i, 0, 0);
        }
    }

    debug {
        writeln(adj);
    }

    alias Vet = Tuple!(int, "v", int, "c", int, "d");
    auto bh = new BinaryHeap!(Array!Vet, "a.d > b.d")();
    dist[0][0] = 0;
    bh.insert(Vet(0, 0, 0));

    while (!bh.empty) {
        auto v = bh.front;
        bh.removeFront;

        if (v.d > dist[v.v][v.c]) continue;

        if (v.v == n - 1) {
            writeln(v.d);
            return;
        }

        if (v.c !in adj[v.v]) continue;
        
        foreach (u ; adj[v.v][v.c]) {
            if (dist[u.v][u.c] > v.d + u.cost) {
                dist[u.v][u.c] = v.d + u.cost;
                bh.insert(Vet(u.v, u.c, dist[u.v][u.c]));
            }
        }
    }

    writeln(-1);
}





void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}



void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}
